如何在 NodeJS 中使用 EcmaScript 模块?
CommonJS模块包括exports 和require() 语句的使用,而EcmaScript模块包括import 和export 语句的使用。
在此处了解更多信息:node.js require 和 ES6 导入和导出之间的区别
Node.js 默认将 JS 代码视为CommonJS模块,但是可以使用 EcmaScript模块而不是使用–experimental-modules 标志。
请按照以下提到的步骤操作:
使用以下命令在所需文件夹中为 Node.js 项目初始化 package.json,并根据提示输入值。
npm init
输入以下命令跳过提示:
npm init -y
打开新创建的 package.json 并添加以下字段。
"type":"module"
例子:
- 文件结构:
- 例子:
area.js
const areaOfRectangle = (length, breadth) => { return length * breadth } export default areaOfRectangle
index.js
import areaOfRectangle from './area.js' console.log('Area of rectangle: ', areaOfRectangle(5, 8))
索引.js
import areaOfRectangle from './area.js' console.log('Area of rectangle: ', areaOfRectangle(5, 8))
输出: