前端模块化

常见的模块化规范

CommonJS、AMD、CMD,也有ES6的Modules。

CommonJS

模块化有两个核心:导出和导入

CommonJS的导出:

1
2
3
4
5
6
7
8
9
module.exports = {
flag:ture,
test(a,b){
return a + b
},
demo(a,b){
return a * b
}
}

CommonJS的导入:

1
2
3
4
5
6
7
//CommonJS模块
let {test,demo,flag} = require('moduleA');
//等同于
let_mA = require('moduleA');
let test = _mA.test;
let demo = _mA.demo;
let flag = _mA.flag;

ES6的export和import

export基本使用

export指令用于导出变量

1
2
3
4
5
6
7
//info.js
export let name = 'cjy'
export let age = 18
//另一种写法
let name = 'cjy'
let age = 18
export{name,age}

export指令用于导出函数或类

1
2
3
4
5
6
7
8
9
10
11
12
13
function test(content){
console.log(content);
}
class Person{
constructor(name,age){
this.name = name;
this.age = age;
}
run(){
console.log(this.name)
}
}
export{test,Person}

export default的使用

某些情况下,一个模块中包含某个的功能,我们并不希望给这个功能命名,而且让导入者可以自己来命名,这个时候就可以使用export default

1
2
3
4
5
6
7
//info.js
export default function(){
console.log('default function');
}
//main.js
import myFunc from './info.js'
myFunc

export default在同一个模块中,不允许同时存在多个。

import基本使用

  1. 使用export指令导出了模块对外提供的接口,就可以通过import命令来加载对应的这个模块

  2. 首先,我们需要在HTML代码中引入两个js文件,并且类型需要设置为module

    1
    2
    <script src="info.js" type="module"></script>
    <script src="main.js" type="module"></script>
  1. import指令用于导入模块中的内容,比如info.js的代码

    1
    2
    import{name,age} from "./info.js"
    console.log(name,age)

*通过可以导入模块中所有的export变量,但是通常情况下我们需要给起一个别名,方便后续的使用**

1
import * as info from './info.js'

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!