在 ES6 Node.js 中导入 '.json' 扩展会抛出错误
Import '.json' extension in ES6 Node.js throws an error
我们正在尝试通过 Node.js 使用 ES6 导出和导入模块的新方法。从 package.json
文件中获取版本号对我们来说很重要。下面的代码应该这样做:
import {name, version} from '../../package.json'
但是,在执行时抛出以下错误:
TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".json" for T:\ICP\package.json imported from T:\ICP\src\controllers\about.js
我们有什么遗漏的吗?
是否不支持扩展 .json
?
是否有另一种方法可以使用 Node.js 13+?
检索此信息
尝试使用
process.env.npm_package_version
this might help you
According to the Node.js ES Modules docs --experimental-json-modules. is required for importing JSON files.
包括 --experimental-json-modules 标志以使模块工作。
node --experimental-json-modules about.js
是的,还有另一种获取版本的方法,但它没有 ES6
模块系统。这是一个工作示例:https://codesandbox.io/s/funny-banzai-2xgvf.
您仍然可以在 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
您可以像在文档 node-js 中那样使用它,如下所示:
import { readFile } from 'fs/promises';
const json = JSON.parse(await readFile(new URL('../../package.json', import.meta.url)));
我们正在尝试通过 Node.js 使用 ES6 导出和导入模块的新方法。从 package.json
文件中获取版本号对我们来说很重要。下面的代码应该这样做:
import {name, version} from '../../package.json'
但是,在执行时抛出以下错误:
TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".json" for T:\ICP\package.json imported from T:\ICP\src\controllers\about.js
我们有什么遗漏的吗?
是否不支持扩展 .json
?
是否有另一种方法可以使用 Node.js 13+?
尝试使用
process.env.npm_package_version
this might help you
According to the Node.js ES Modules docs --experimental-json-modules. is required for importing JSON files.
包括 --experimental-json-modules 标志以使模块工作。
node --experimental-json-modules about.js
是的,还有另一种获取版本的方法,但它没有 ES6
模块系统。这是一个工作示例:https://codesandbox.io/s/funny-banzai-2xgvf.
您仍然可以在 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
您可以像在文档 node-js 中那样使用它,如下所示:
import { readFile } from 'fs/promises';
const json = JSON.parse(await readFile(new URL('../../package.json', import.meta.url)));