zhaobinglong / myBlog

https://zhaobinglong.github.io/myBlog/
MIT License
7 stars 0 forks source link

js概念之模块化 #66

Open zhaobinglong opened 4 years ago

zhaobinglong commented 4 years ago

CommonJs

2009年Nodejs发布,其中Commonjs是作为Node中模块化规范以及原生模块面世的。Node中提出的Commonjs规范具有以下特点:

基本上Commonjs发布之后,就成了Node里面标准的模块化管理工具。同时Node还推出了npm包管理工具,npm平台上的包均满足Commonjs规范,随着Node与npm的发展,Commonjs影响力也越来越大,并且促进了后面模块化工具的发展,具有里程碑意义的模块化工具

var a = require('./a');
var b = require('./b');

console.log(a.aNum, b.bStr);

参考

https://zhuanlan.zhihu.com/p/33843378 https://www.cnblogs.com/mengfangui/p/9073459.html

zhaobinglong commented 4 years ago

ES6新增import/export

之前的各种方法和框架,都出自于各个大公司或者社区,都是民间出台的结局方法。到了2015年,ES6规范中,终于将模块化纳入JavaScript标准,从此js模块化被官方扶正,也是未来js的标准。

导入

// 导入模块中的一个功能
import {aNum} from './a';

// 导入整个模块
import _ from 'lodash'

导出export/export default

// export和export default可以同时存在
// export可以多个,但是export default只能存在一次

// 在同一个文件中,export导出两次
// export default一次
export baseUrl = 'http://127.0.0.1'
export function fn1 () {
      //do something
}
export default function fn2 () {
      //do something
}
zhaobinglong commented 3 years ago

两种模块化的区别

zhaobinglong commented 3 years ago

AMD和CMD

参考

https://www.zhihu.com/question/20351507

zhaobinglong commented 3 years ago

导出和导入的对应

// 导出一个默认的对象
export default {
    name: '名称',
    naturalUnit: '自然单位', 
    jfUnit: '换算单位',  
    chargeUnit: '换算单位',    
    unitLocation: '单位位置'
}

// 导入上面这个对象
import para from '@/libs/index'
para.name