node的两种模块化规范:
CommonJS
模块化规范和
ES
模块化规范
两种模块化的关系的:CommonJS
模块化规范是nodejs最开始使用的模块化规范,但是由于ES
模块化规范的盛行使得nodejs不得不使用ES
模块化规范。
两种模块化规范的切换
node默认使用的是CommonJS模块化规范,可以通过package.json配置文件的type
属性进行修改。
type
有两个取值module
和commonjs
,默认使用的是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
ES
使用的是 export、export default 和 import