简体   繁体   English

从 angular 库访问 package.json

[英]Access package.json from angular library

I'm building an angular library and got stuck trying to access package.json file in the integrating app.我正在构建一个 angular 库,但在尝试访问集成应用程序中的package.json文件时被卡住了。

My purpose is to read the app-version variable from the integrating app.我的目的是从集成应用程序中读取 app-version 变量。

this is what I thought:这就是我的想法:

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


@Injectable({
  providedIn: 'root'
})
export class AppVersionService {

  private version: string = version;

  getVersion() {
    return this.version;
  }
}

Logically I'm getting this error:从逻辑上讲,我收到此错误:

ERROR: error TS6059: File 'C:/.workspace/app-versioning/package.json' is not under 'rootDir' 'C:\.workspace\app-versioninge\projects\app-versioning\ng-core'. 'rootDir' is expected to contain all source files.

PS: I need to load just the app-version variable into the browser, not the whole package.json file. PS:我只需要将 app-version 变量加载到浏览器中,而不是整个package.json文件。

Any Ideas, Thanks!任何想法,谢谢!

You can use require to obtain the file package.json .您可以使用require获取文件package.json

One good and clean practice is to exported using the environment.一种良好且干净的做法是使用环境导出。 To do this just request the file in environment.ts, and export the data you want, something like this为此,只需请求 environment.ts 中的文件,然后导出您想要的数据,就像这样

const packageJson = require('../../package.json');
export const environment = {
  ..
  version: packageJson.version
}

Of course you have to correct the number .. to the file.当然,您必须将数字..更正到文件中。

UPDATE :更新

angular-ngrx-material-starterangular-ngrx-材料启动器

This angular starter project include interesting tools for development and several good practices including the one I mention in the answer.这个 angular starter 项目包括有趣的开发工具和一些好的实践,包括我在答案中提到的那个。 I thought it is was worth to add it to the answer.我认为值得将其添加到答案中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM