gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 21:28:43 25 4
gpt4 key购买 nike

我正在尝试从 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
}
}

当 require 试图解析 json 文件时,我得到了 Error: (SystemJS) Unexpected token:。当我将鼠标悬停在 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"
},

最佳答案

您遇到的问题是 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 加载器。我从不这样做。相反,我在我的配置中设置了一个 meta 来告诉 SystemJS,“加载此文件时使用 json 加载器”:

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

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

关于json - 如何从 package.json 加载 Angular (v4+)应用程序的版本号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47166490/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com