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