如何从角度库中的package.json获取版本

时间:2019-12-17 16:05:43

标签: angular typescript

我无法在Angle的库中包含package.json的版本,但是它可以在项目中使用。我这样使用import:

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

并出现以下错误:

ERROR: error TS6059: File '/Users/.../library/package.json' is not under 'rootDir' '/Users/.../library/src'. 'rootDir' is expected to contain all source files.

An unhandled exception occurred: error TS6059: File '/Users/.../library/package.json' is not under 'rootDir' '/Users/.../library/src'. 'rootDir' is expected to contain all source files.

See "/private/var/folders/tw/z8v0wkt50g5876740n99hzy00000gp/T/ng-0JDpjC/angular-errors.log" for further details.

通过require的方式包括整个package.json,这会带来安全风险。 import { version } from '../../package.json'仅包含版本号,但适用于有角度的应用程序,不适用于库。

2 个答案:

答案 0 :(得分:1)

您可以像常规模块一样将其导入:

import { version } from 'package.json'

但是请确保在tsconfig.json中将"resolveJsonModule": true添加到compilerOptions

答案 1 :(得分:0)

此代码如何:

const packageJson = require('../../package.json');
console.log(packageJson.version);