Node.js 默认使用CJS(CommonJS)规范 (即 require 和 module.exports)
而不是ESM(ES Modules)规范 (即 import 和 export)
ESM规范
方式1 - 配置package.json
demo.js
//从 web.js 文件中导入 title、url、getUrl
import obj from "./web.js"
console.log(obj.title)
console.log(obj.url)
console.log(obj.getUrl())
web.js
let title = "邓瑞编程"
let url = "dengruicode.com"
let getUrl = () => "www.dengruicode.com"
//将一个对象作为整体导出, 导出的对象包含 title、url、getUrl
export default { title, url, getUrl }
package.json
{
"type": "module",
"name": "demo",
"version": "1.0.0",
"main": "demo.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"description": ""
}
方式2 - mjs
demo.mjs
//从 web.js 文件中导入 title、url、getUrl
import obj from "./web.mjs"
console.log(obj.title)
console.log(obj.url)
console.log(obj.getUrl())
web.mjs
let title = "邓瑞编程"
let url = "dengruicode.com"
let getUrl = () => "www.dengruicode.com"
//将一个对象作为整体导出, 导出的对象包含 title、url、getUrl
export default { title, url, getUrl }
CJS规范
demo.js
//从 web.js 文件中导入 title、url、getUrl
//import obj from "./web.js" //ESM规范
const obj = require("./web.js") //CJS规范
console.log(obj.title)
console.log(obj.url)
console.log(obj.getUrl())
web.js
let title = "邓瑞编程"
let url = "dengruicode.com"
let getUrl = () => "www.dengruicode.com"
//将一个对象作为整体导出, 导出的对象包含 title、url、getUrl
//export default { title, url, getUrl } //ESM规范
module.exports = { title, url, getUrl } //CJS规范
注
Node.js 新项目建议使用ESM规范