node的两种模块化规范


node的两种模块化规范: CommonJS模块化规范和 ES模块化规范

两种模块化的关系的:CommonJS模块化规范是nodejs最开始使用的模块化规范,但是由于ES模块化规范的盛行使得nodejs不得不使用ES模块化规范。

两种模块化规范的切换

node默认使用的是CommonJS模块化规范,可以通过package.json配置文件的type属性进行修改。
type有两个取值modulecommonjs,默认使用的是commonjs
module代表ES6规范
commonjs代表CommonJS规范
eg:

{
  "dependencies": {
    "math": "^0.0.3",
    "md5": "^2.3.0",
    "nrm": "^0.2.0"
  },
  "name": "node",
  "version": "1.0.0",
  "main": "a.js",
  "type": "module",
  "devDependencies": {
    "coffee-script": "^1.7.1"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "description": ""
}

CommonJS模块化规范和ES模块化规范示例

以暴露和导入文件为例

  • CommonJS使用的是 exports、module.exportsh和require
    使用时记得设置: "type": "commonjs",
    使用CommonJS规范,引入文件的路径名后的.js文件名后缀可以省略。
  • ES使用的是 export、export default 和 import
    使用时记得设置: "type": "module",
    使用ES6规范,引入文件的路径名后的.js文件名后缀不可以省略。

exports、module.exportsh和require使用——node模块使用_CommomJS规范
export、export default 和 import使用

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值