有没有方法在nodejs应用程序中获取package.json中设置的版本?我想要这样的东西

var port = process.env.PORT || 3000
app.listen port
console.log "Express server listening on port %d in %s mode %s", app.address().port, app.settings.env, app.VERSION

当前回答

const{version}=require(“./package.json”);console.log(版本);const v=require(“./package.json”).version;控制台日志(v);

其他回答

我知道这不是OP的意图,但我只是不得不这样做,所以希望这对下一个人有所帮助。

如果您在CI/CD过程中使用docker compose,您可以通过这种方式获得它!

version:
  image: node:7-alpine
  volumes:
    - .:/usr/src/service/
  working_dir: /usr/src/service/
  command: ash -c "node -p \"require('./package.json').version.replace('\n', '')\""

对于图像,可以使用任何节点图像。我用阿尔卑斯山因为它是最小的。

用于以下web组件的版本:

const { version } = require('../package.json')

class Widget extends HTMLElement {

  constructor() {
    super()
    this.attachShadow({ mode: 'open' })
  }

  public connectedCallback(): void {
    this.renderWidget()
  }

  public renderWidget = (): void => {
    this.shadowRoot?.appendChild(this.setPageTemplate())
    this.setAttribute('version', version)
  }
}

如果使用rollup,可以使用rollup插件替换插件来添加版本,而无需向客户端公开package.json。

// rollup.config.js

import pkg from './package.json';
import { terser } from "rollup-plugin-terser";
import resolve from 'rollup-plugin-node-resolve';
import commonJS from 'rollup-plugin-commonjs'
import replace from 'rollup-plugin-replace';

export default {
  plugins: [
    replace({
      exclude: 'node_modules/**',
      'MY_PACKAGE_JSON_VERSION': pkg.version, // will replace 'MY_PACKAGE_JSON_VERSION' with package.json version throughout source code
    }),
  ]
};

然后,在源代码中,您可以在任何需要package.json版本的地方使用字符串“MY_package_json_version”。

// src/index.js
export const packageVersion = 'MY_PACKAGE_JSON_VERSION' // replaced with actual version number in rollup.config.js

使用ES6模块,您可以执行以下操作:

import {version} from './package.json';

一个安全的选项是添加一个npm脚本,该脚本生成一个单独的版本文件:

"scripts": {
    "build": "yarn version:output && blitz build",
    "version:output": "echo 'export const Version = { version: \"'$npm_package_version.$(date +%s)'\" }' > version.js"
  }

这将输出包含以下内容的version.js:

export const Version = { version: "1.0.1.1622225484" }