module.exports和exports是属于commonJs规范
export和export default是ES6模块规范
-
commonjs模块输出的是值的浅拷贝,输出后被改变,其他引用模块不会改变
同步
存在本地硬盘,加载快
node.js
运行时加载
浏览器不支持 -
ES6模块输出的是值的引用 (输出后被改变,其他引用模块会改变)
编译时输出接口
webpack的tree-shaking只能作用于ES6模块,就是因为ES6模块在编译时就能确定依赖
node 运行文件不支持es6语法
浏览器不支持,支持es5
babel和webpack本身都是遵循commonjs
- babel把es6转为es5,还是遵循commonjs
- webpack会讲commonjs最终打包成浏览器可识别的内容
// vuecli的babel.config.js
module.exports = {
presets: ['@vue/cli-plugin-babel/preset'],
env: {
development: {
// 将import转为require
plugins: ['dynamic-import-node'],
},
},
}
// .browserslistrc
> 1%
last 2 versions
not dead
因此,可以在js里写commonjs或者es6,但是node的运行js文件不能使用es6,node的js还没有将该文件编译 且 node环境只能识别commonjs
jsconfig.json //由ts而来,jsconfig.json相当于tsconfig.json的“allowJs”属性设置为true
{
"compilerOptions": {
// 被编译为的ES的版本
"target": "ES6",
// 模块化规范
"module": "commonjs",
"allowSyntheticDefaultImports": true,
"baseUrl": "./",
// 别名import可用@
"paths": {
"@/*": ["src/*"]
}
},
"exclude": ["node_modules", "dist"]
}
common.js
const test:object | array;
module.exports = test;
const fn = ()=>{}
exports.fn = fn
module.exports如下:
var app = {
name: 'app',
version: '1.0.0',
sayName: function(name){
console.log(this.name);
}
}
module.exports = app;
/**
* @description js直接requrie获取,相对路径
**/
var app = require('./app.js');
const { name } = require('./app.js');
app.sayName('hello');//hello
/**
* @description import
**/
import { name } '@/app.js'
exports.如下:
const fn = ()=>{}
exports.fn = fn
/**
* @description js直接requrie获取
**/
var fn = require("./functions");
fns.fn();