如何在 TypeScript 中导入 package.json?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50822310/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:28:44  来源:igfitidea点击:

How to import package.json in TypeScript?

jsontypescript

提问by twofifty6

I'm trying to import my package.json file in TypeScript and it doesn't seem to work. Specifically, I'm just trying to import it so that I can access the name and version properties for a log statement. Something like:

我正在尝试在 TypeScript 中导入我的 package.json 文件,但它似乎不起作用。具体来说,我只是想导入它,以便我可以访问日志语句的名称和版本属性。就像是:

import * as pjson from '../package.json';
// other code here
log.info(`${pjson.name}:${pjson.version}` started on port ...);

We have this same syntax elsewhere in other projects that use Node/Babel, but I'm trying to introduce some TypeScript around these parts. Elsewhere we'd do something like:

我们在其他使用 Node/Babel 的项目的其他地方也有相同的语法,但我试图围绕这些部分引入一些 TypeScript。在其他地方,我们会做类似的事情:

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

That doesn't work here however. I followed the instructions at https://www.npmjs.com/package/json-d-tswhich at least made the error on my import statement go away, but now when I try to access properties I get the following error:

然而,这在这里不起作用。我按照https://www.npmjs.com/package/json-d-ts上的说明进行操作,这至少使我的导入语句中的错误消失了,但是现在当我尝试访问属性时,出现以下错误:

src/index.ts(20,21): error TS2339: Property 'name' does not exist on type 'typeof import("*.json")'.
src/index.ts(20,35): error TS2339: Property 'version' does not exist on type 'typeof import("*.json")'.

Is there a way to fix this, or do I just have to hardcode these values somewhere (rather than dynamically retrieving them from package.json)? Maybe I can declare a type for import("*.json")somehow with these properties defined on it?

有没有办法解决这个问题,或者我是否只需要在某处硬编码这些值(而不是从 package.json 动态检索它们)?也许我可以import("*.json")用在上面定义的这些属性以某种方式声明一个类型?

采纳答案by Sly321

Since TypeScript 2.9 you can import JSON files as described here: typescriptlang documentation 2.9#json, for this you need to enable the "resolveJsonModule" option in your tsconfig.json.

从 TypeScript 2.9 开始,您可以按照此处所述导入 JSON 文件: typescriptlang 文档 2.9#json,为此您需要在 tsconfig.json 中启用“resolveJsonModule”选项。

You need typescript version 2.9 in your project:

您的项目中需要 typescript 2.9 版:

npm i typescript@latest --saveor yarn add typescript

npm i typescript@latest --save或者 yarn add typescript

if you are building the typescript files from the command line with tsc, you will need to install the latest typescript version globally:

如果您从命令行使用 构建打字稿文件tsc,则需要全局安装最新的打字稿版本:

npm i -g typescript@latestor yarn global add typescript

npm i -g typescript@latest或者 yarn global add typescript

if you are building your project with webpackand webpack-dev-serveryou need to make sure that jsonfiles are hosted in the webpack-dev-servercontext as static files. And even if you hosted them, you can't importjson files in the web environment like this, you would need to load the jsonfile with an ajaxrequest and parse the response with JSON.parse.

如果您正在构建您的项目,webpack并且webpack-dev-server您需要确保json文件webpack-dev-server作为静态文件托管在上下文中。即使您托管了它们,您也不能import像这样在 Web 环境中生成 json 文件,您需要json使用ajax请求加载文件并使用 .json 解析响应JSON.parse

回答by sebilasse

How to import *.json ?

如何导入 *.json ?

As already answered you need Typescript >= 2.9 and the following settings in tsconfig.json:

正如已经回答的那样,您需要 Typescript >= 2.9 和以下设置tsconfig.json

{
  "resolveJsonModule": true,
  "esModuleInterop": true,
  "module": "commonjs"
}

But there are restrictions:

但是有限制:

  • You must compile to CommonJS
  • All your imported JSONs must reside under the "rootDir"
  • 您必须编译为 CommonJS
  • 所有导入的 JSON 必须位于 "rootDir"

Unfortunately the "rootDir"is very often a folder beneathpackage.json like './src' and things would fail.

不幸的"rootDir"是,它通常是package.json下的一个文件夹例如 './src' 并且事情会失败。

So:
How to import package.json ? You can requireit:
const pjson = require('../package.json');

那么:
如何导入 package.json ?您可以require它:
const pjson = require('../package.json');

If you use npm.start: you don't need to :

如果你使用 npm.start:你不需要:

The package.json fields are tacked onto the npm_package_ prefix. So, for instance, if you had {"name":"foo", "version":"1.2.5"} in your package.json file, then your package scripts would have the npm_package_name environment variable set to “foo”, and the npm_package_version set to “1.2.5”. You can access these variables in your code with process.env.npm_package_name and process.env.npm_package_version, and so on for other fields.

package.json 字段附加到 npm_package_ 前缀上。因此,例如,如果您的 package.json 文件中有 {"name":"foo", "version":"1.2.5"},那么您的包脚本会将 npm_package_name 环境变量设置为“foo”,并且 npm_package_version 设置为“1.2.5”。您可以在代码中使用 process.env.npm_package_name 和 process.env.npm_package_version 访问这些变量,等等其他字段。

回答by Sami

npm exports package.jsonattributes as env vars with the the prefix npm_package_as described in npm docs
So if you're using npm you can get the version as process.env.npm_package_version

npm 将package.json属性导出为带有npm 文档中npm_package_描述的前缀的 env vars 因此,如果您使用 npm,您可以获得版本为
process.env.npm_package_version

回答by Corey Jallen

Typescript should be able to do it as follows:

打字稿应该能够做到如下:

import package from "../package.json"

// access name and version like this:

console.log(package.name);

Check out the third grey box under Support for well-typed JSON imports.
https://blogs.msdn.microsoft.com/typescript/2018/05/31/announcing-typescript-2-9/#json-imports

查看支持类型良好的 JSON 导入下的第三个灰色框。
https://blogs.msdn.microsoft.com/typescript/2018/05/31/annoucing-typescript-2-9/#json-imports

回答by fider

  1. Ensure tsconfig.json compiler options contains:

    "resolveJsonModule": true, "esModuleInterop": true, "module": "commonjs"

  2. Import package.json with typings

    import * as pack from '../package.json';

  1. 确保 tsconfig.json 编译器选项包含:

    "resolveJsonModule": true, "esModuleInterop": true, "module": "commonjs"

  2. 与进口的package.json分型

    import * as pack from '../package.json';