如何从package.json加载角度(v4 +)应用程序中的版本号



我正在尝试从package.json加载我的Angular应用程序的版本号,因为那是版本号所在的位置。在查找如何执行此操作时,大多数人建议使用 require 来加载 json 文件,如下所示:

var pckg = require('../../package.json');
console.log(pckg.version);

当我将此代码放入组件的构造函数中时,我变得未定义。

接下来,我尝试通过导入将 require 语句放在组件上方,例如:

const { version: appVersion } = require('../../package.json')
export class StackOverflowComponent {
  public appVersion
  constructor() {
    this.appVersion = appVersion
  }
}

我收到错误:(SystemJS)意外令牌:当要求尝试解析 json 文件时。当我将鼠标悬停在require上时,我看到它的类型是"NodeRequire(id:string)"。这与 requirejs 有什么不同吗?

正在使用systemjs,我注意到很多有答案的人都指的是Webpack。以下是可以帮助您回答我的问题的相关文件。

tsconfig.json:

{
  "compilerOptions": {
   "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": ["es2015", "dom"],
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true,
    "allowSyntheticDefaultImports": true,
    "typeRoots": [
      "./node_modules/@types/"
    ]
  },
  "compileOnSave": true,
   "exclude": [
    "node_modules/*",
    "**/*-aot.ts"
  ]
}

devDependencies in package.json:

"devDependencies": {
    "@types/node": "^6.0.46",
    "concurrently": "^3.0.0",
    "lite-server": "^2.3.0",
    "rollup": "^0.50.0",
    "rollup-plugin-commonjs": "^8.2.1",
    "rollup-plugin-node-resolve": "^3.0.0",
    "rollup-plugin-uglify": "^2.0.1",
    "source-map-explorer": "^1.5.0",
    "typescript": "~2.3.2"
  },

您遇到的问题是 SystemJS 试图将 JSON 文件解释为可执行文件。为了让SystemJS明智地加载JSON文件,你需要使用像systemjs-plugin-json这样的JSON加载器。

您需要使其在您的 SystemJS 配置中可用。例如,我使用:

SystemJS.config({
  paths: {
    // Set an abbreviation to avoid having to type /node_modules/ all the time.
    "npm:": "/node_modules/",
    // ....
  },
  map: {
    // The loader is known to SystemJS under the name "json".
    json: "npm:systemjs-plugin-json",
    // ...
  },
  packageConfigPaths: [
    // Tell SystemJS that it should check the package.json files 
    // when figuring out the entry point of packages. If you omit this, then
    // the map above would have to be "npm:systemjs-plugin-json/json.js".
    "npm:*/package.json",
    // ...
  ],
});

然后你需要使用它。你可以用require('../../package.json!json');替换你的require调用,但我怀疑TypeScript不会因为时髦的模块名称而对此感到满意。!json部分告诉 SystemJS 使用 json 加载器。我从不这样做。相反,我在配置中设置了一个meta,告诉 SystemJS,"加载此文件时使用json加载程序":

SystemJS.config({
  meta: {
    "path/to/package.json": {
      loader: "json",
    },
  },
});

您需要根据 SystemJS 配置的其余部分(特别是baseUrl)找出path/to/package.json

如果您将

以下内容添加到您的键入中.d.ts:

declare module '*.json' {
  const value: any;
  export default value;
}

然后,您可以执行以下操作:

import * as pkg from '../path-to-root/package.json';

然后像这样引用它,例如在组件的构造函数中:

 console.log(`version: ${pkg['version']}`);

或者,等效地,

console.log(`version: ${(<any>pkg).version}`);

最新更新