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

问题描述 投票:2回答:2

我试图从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)意外的令牌:当require试图解析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"
  ]
}

package.json中的devDependencies:

"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"
  },
json angular typescript systemjs
2个回答
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替换你的require('../../package.json!json');调用,但我怀疑TypeScript因为时髦的模块名称而对此不满意。 !json部分告诉SystemJS使用json加载器。我从来没有这样做过。相反,我在配置中设置了一个告诉SystemJS的meta,“在加载此文件时使用json加载器”:

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

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


1
投票

如果您将以下内容添加到typings.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}`);
© www.soinside.com 2019 - 2024. All rights reserved.