avatar

目录
CommonJS规范和ES6模块规范
-

CommonJS规范

Node 应用由模块组成,采用 CommonJS 规范

导出模块采用module.exports,module.exports是一个对象,也是导出的接口

导入模块采用require引入这个对象

javascript
// example.js
let x = 5
var add3 = function(value){
return 3 + value
}

导出和引入 example.js 中的模块

挂载 module.exports 对象上导出和引入

javascript
// 导出1,分别导出
module.exports.x = x
module.exports.add3 = add3
// 导出2,对象解构赋值
module.exports = {x, add3}
// 引入1,解构赋值
let {x,add3} = require('./example.js')
// 引入2,整个对象
let example = require('./example.js')
example.add3(5)

只导出一个目标时,不使用对象形式

Javascript
// 导出
moduel.exports = add3
// 引入
let add3 = require('./example.js')

ES6模块规范

export命令用于规定模块的对外接口,import命令用于引入其他模块提供的功能。

导出和引入 example.js 中的模块

javascript
// example.js
let x = 5
var add3 = function(value){
return 3 + value
}
javascript
// 导出
export {x, add3}
// 引入1,对象解构赋值
import {x, add3} from './example.js'
// 引入2,使用 * 指定一个对象,所有输出值都加载到这个对象上
import * as example from './example.js'
example.add3(5)

只导出一个目标时使用 export default

Javascript
// 导出 
export default add3
// 引入
import add3 from './example.js'

浏览器加载 ES6 模块

浏览器加载 ES6 模块,也使用<script>标签,但是要加入type="module"属性

html
<script type="module" src="./test.js"></script>

上面代码在网页中插入一个模块test.js,由于 type 属性设置为 module,所以浏览器知道这是一个 ES6 模块

浏览器对于type=module<script>,都是异步加载,相当于设置了defer属性,延迟脚本会等到整个页面渲染完再执行模块脚本,避免浏览器阻塞。

如果页面有多个<script type="module">,它们会按照在页面的顺序依次执行

文章作者: GRIT
文章链接: https://grit0821.github.io/Blog/2020/01/21/CommonJS%E8%A7%84%E8%8C%83%E5%92%8CES6%E6%A8%A1%E5%9D%97%E8%A7%84%E8%8C%83/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Grit's World