package.json
{
"name": "test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"engines": {
"node": ">=20.15.0 <21"
},
"type": "module",
"scripts": {
"start": "node index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"jsonfile": "^6.1.0"
}
}
其中 jsonfile 为commonjs规范定义的库,type: module 指定按es6规范解析js文件。
index中如果想要使用 jsonfile 库,则方法如下(index.js):
import { createRequire } from 'node:module';
const require = createRequire(import.meta.url);
const jsonfile = require('jsonfile');
jsonfile.writeFileSync(test.json
, {x:'测试数据'})