在 ES6 Node.js 中导入’. json’扩展名会抛出一个错误

我们正在尝试使用 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 + 检索此信息还有其他方法吗?

58141 次浏览

try to use

process.env.npm_package_version

this might help you

From Node.js version 17.5.0 onward, importing a JSON file is possible using Import Assertions:

import packageFile from "../../package.json" assert { type: "json" };


const {
name,
version
} = packageFile;
  • assert { type: "json" } is mandatory
  • Destructuring such as { name, version } is not possible in the import declaration directly
  • The contents of the JSON file are exported as a default export, so they need to be imported from default.

The dynamic import version looks like this:

const {
default: {
name,
version
}
} = await import("../../package.json", {
assert: {
type: "json"
}
});

Since import assertions and JSON modules have only recently promoted to stage 3, older versions of Node.js might have supported an older syntax. According to the compatibility tables on MDN for import declarations and dynamic import, older versions of Node.js (16.0.0 – 16.14.0 and 17.0.0 – 17.4.0) had varying support:

  • These versions required the --experimental-json-modules flag:

    node --experimental-json-modules about.js
    
  • Some versions did not support import assertions on dynamic import

  • Some versions did not support the "json" type, specifically

  • Some versions relied on an older proposal which did not specify the assert syntax yet

You can sill import require in an ES6 module for Node.js:

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:

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:

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

And run it with the matching experimental flag:

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