Skip to content

CommonJS 与 ES6 模块化基础语法

Published: at 13:02

目前主要的 js 模块化还有 CommonJS 和 ES6 Modules,以下是相关的一些笔记记录。

CommonJS 规范

每个文件就是一个模块,有自己的作用域。在一个文件里面定义的变量、函数、类,都是私有的,对其他文件不可见。

CommonJS 模块化的写法,需要 node 等环境支持。 在浏览器中无法直接解析和运行,需要先编译。

CommonJS 导出

module.exports = {
// 在此对象中定义导出的变量或函数
flag: true,
name: "xxx",
add(num1, num2){
return num1 + num2;
},
}
// 在这里定义变量,函数。
module.exports = {
导出名称1: 导出的成员1,
导出名称2: 导出的成员2,
}
// 在这里定义变量,函数。
module.exports = {
导出的成员1,
导出的成员2,
}

CommonJS 导入

let {flag, name, add} = require('./xxx.js');
const xxx = require('./xxx.js')
// 使用:
xxx.导出的成员1;
xxx.导出的成员2;

commonjs 详解

【尚硅谷】快速入门nodejs_模块化详解_哔哩哔哩_bilibili

ES6 的模块化实现

在浏览器中使用 ES6 模块化,需要声明 js 的 type 为 module,

<script src = './xxx.js' type='module'></script>

每个模块(文件)内部的变量是私有的,其它模块(文件)无法直接访问。

ES6 模块导出

// 在这里定义变量,函数。
flag: true,
name: "xxx",
add(num1, num2){
return num1 + num2;
},
// 导出
export {
flag, name, add
}
// 导出变量
export let myFlag = true;
// 导出函数
export function sum(a, b){
return a + b;
}
// 导出类
export class Person{
name: 'jgrass',
run(){
console.log(`${this.name} run`)
}
}

export default 只能有一个,使用方导入时可以自定义命名。 所以,一般使用 export default 导出一个对象,而不是单个的变量或者函数。

// 导出 aaa.js
let address = "广州市";
export default address
// 导入 bbb.js
import addr/*自定义命名*/ from './aaa.js'
// 导出 aaa.js
// 不命名,外部使用者命名
export default function(args){
}
// 导入 bbb.js
import myFunction/*自定义命名*/ from './aaa.js'
let args = {};
myFunction(args);
// 导出 aaa.js
// 导出对象,不命名,外部使用者命名
export default {
name: "jgrass.cc"
}
// 导入 bbb.js
import obj/*自定义命名*/ from './aaa.js'
let n = obj.name;

ES6 模块导入

import {flag, add, Person} from "./xxx.js"
let p = new Persion();
p.run();
import * as xModule/*自定义命名*/ from "./xxx.js"
let f = xModule.flag;
import myModule/*自定义命名,没有大括号*/ from "./xxx.js"

参考资料

扩展阅读


原文链接: https://blog.jgrass.cc/posts/common-js-es6-module/

本作品采用 「署名 4.0 国际」 许可协议进行许可,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接。