Node 14开始,开始反对ES module语法。
JSON模块工作在Node.js版本>=17.1
中,也能够应用--experimental-json-modules
标记启用Experimental JSON
模块
/* Experimental JSON import in Node.js $ node index.mjs*/// An import assertion in a static importimport info from `./package.json` assert { type: `json` };// An import assertion in a dynamic importconst { default: info } = await import("./package.json", { assert: { type: "json", },});
我曾经习惯在node.js应用require
导入json,例如const data = require('./some-file.json')
,下面的写法无疑让人感到丧气。
如果你还不想应用这个实验性的性能,这篇文章解释了在ES模块中解决JSON的办法。
1. 手动读取和解析JSON文件
其实就是应用fs
模块读取文件,而后再用JSON.parse
解析。
import { readFile } from 'fs/promises';const json = JSON.parse( await readFile( new URL('./some-file.json', import.meta.url) ));
2. 利用CommonJS的require函数来加载JSON文件(举荐)
import { createRequire } from "module";const require = createRequire(import.meta.url);const data = require("./data.json");
createRequire
容许你结构一个CommonJS require函数来应用CommonJS的典型性能,例如在Node.js的EcmaScript模块中读取JSON。
总结
import assertions
无疑是将来ES modules导入json的最佳抉择,但惋惜它目前仍然是试验性功能。至于介绍的2种代替计划,其实都不是最佳计划,但不影响你解决问题。
参考文章
- 厉害了,ECMAScript 新提案:JSON模块
- How to import JSON files in ES modules (Node.js)