Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JavaScript 模块化 #24

Open
vivipure opened this issue Aug 8, 2022 · 3 comments
Open

JavaScript 模块化 #24

vivipure opened this issue Aug 8, 2022 · 3 comments

Comments

@vivipure
Copy link
Owner

vivipure commented Aug 8, 2022

CommonJS

定义

CommonJS 规范定义了 exports 导出模块,require引入模块。Node.js 实现了 CommonJS 规范

module.exports = {
   name: "aa",
   age: 12,
}
//   等同于
exports.name = 'aa'
exports.age = 12
// ❌
exports = {
   name: "aa",
   age: 12,
}

Node.js 中每个模块都可以看作一个 module 对象,表示当前模块的信息,通过 module.exports 进行导出。

Node.js 使用 require 进行导入模块

const  a = require('./a'.js)
a.name
a.age

特点

  1. 导出的值是当前模块导出值的浅拷贝
  2. 运行时加载,所以可以在函数内动态加载
  3. 同步加载,有缓存

补充

Node.js 的寻包机制: TODO

@vivipure
Copy link
Owner Author

vivipure commented Aug 8, 2022

AMD

由于 CommonJS 时同步加载的,加载过多模块时,可能会造成浏览器卡顿,影响用户使用体验,并不适合浏览器端使用。

AMD(Asynchronous Module Definition ) 异步加载的模块规范,使用define 定义模块.

代码:

// a.js
define(function (){
   var add = function (x,y){
     return x+y;
   };
   return {
     add: add
   };
 });
// index.js
require(['A'], function (A){
  console.log(A)
       //{add:function}
});

备注: 作为时代的弃子,AMD 在当时的设计还是可以的。

@vivipure
Copy link
Owner Author

vivipure commented Aug 8, 2022

ESM

ESM(ECMAScript Module) 是es6 推出的JS模块化方案。使用 export 导出模块,使用import 导入模块。

// 普通导出
export const a = 1
export {
    a,
    b
}
// ❌
const a 
export a

// 默认导出
export default {}
export default function a() {}
// ❌ 由于默认导出本身为导出 default 值,所以不能进行声明
export default const a = 1

// 导入
// 默认导入
import a from './a.js'
import {default as  a } from './a.js
 
//  部分导入
import {b} from ''./a.js'

// 全部导入
import *  as  A from './a.js'
A.default
A.b
// 导入和导出
export {} from './a.js'
export * as B from './b.js'

特点

  1. 导出的值为引用
  2. 编译时加载,可以用来做 tree-shaking

使用

  1. 使用构建工具进行打包
  2. 在浏览器中使用<script src="./a.js" module></sciprt>进行引用

@vivipure
Copy link
Owner Author

vivipure commented Aug 8, 2022

总结

ESM 是JS的现在和未来, Node.js 高版本已经支持 ESM.

当然对于我们平时开发,写出的库可以打包成 UMD 格式,支持各种规范.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant