简体   繁体   English

在 ES6 Node.js 中导入“.json”扩展会引发错误

[英]Import '.json' extension in ES6 Node.js throws an error

We're trying to use the new ways of exporting and importing modules for ES6 with Node.js.我们正在尝试使用 Node.js 为 ES6 导出和导入模块的新方法。 It's important for us to get the version number from the package.json file.package.json文件中获取版本号对我们来说很重要。 The following code should do that:下面的代码应该做到这一点:

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

However, on execution the following error is thrown:但是,在执行时会引发以下错误:

TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".json" for T:\ICP\package.json imported from T:\ICP\src\controllers\about.js

Is there something we're missing?我们缺少什么吗?
Is the extension .json not supported?不支持扩展名.json吗?
Is there another way to retrieve this information using Node.js 13+?是否有另一种方法可以使用 Node.js 13+ 检索此信息?

According to the Node.js ES Modules docs --experimental-json-modules .根据Node.js ES 模块文档--experimental-json-modules is required for importing JSON files.是导入 JSON 文件所必需的。

Include the --experimental-json-modules flag for the module to work.包括--experimental-json-modules标志以使模块工作。

node --experimental-json-modules about.js

You can sill import require in an ES6 module for Node.js:您可以在 Node.js 的 ES6 模块中导入require

import { createRequire } from "module"; // Bring in the ability to create the 'require' method
const require = createRequire(import.meta.url); // construct the require method
const my_json_file = require("path/to/json/your-json-file.json") // use the require method

You can use it as in docs node-js as follow:您可以在 docs node-js中使用它,如下所示:

import { readFile } from 'fs/promises';

const json = JSON.parse(await readFile(new URL('../../package.json', import.meta.url)));

From Node.js v16 & v18 official documentation:来自 Node.js v16 & v18官方文档:

import SomeJson from './some.json' assert { type: 'json' }

And run it with the matching experimental flag:并使用匹配的实验标志运行它:

node --experimental-json-modules ./your-file.js

yes, there is another way to fetch version, but it is without ES6 module system.是的,还有另一种获取版本的方法,但它没有ES6模块系统。 Here's a working example: https://codesandbox.io/s/funny-banzai-2xgvf .这是一个工作示例: https : //codesandbox.io/s/funny-banzai-2xgvf

try to use尝试使用

process.env.npm_package_version

this might help you 这可能会帮助你

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

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