module

Adrian Yang

Adrian Yang

Front End Engineer

对于前端模块化的理解

什么是模块 什么是模块化?

将一个复杂程序依据一定规则拆分成几个块,并进行组合在一起。

块的内部数据或实现是私有的,只是向外部暴露一些结果方法 和 与其他外部模块的通信

为什么要模块化?

都怼在一个文件的产生的问题

  1. 容易破坏代码 ()
  2. 版本控制冲突
  3. 后期维护困难 (函数重名)
  4. 不便于按需加载

模块化规范

CommonJS_Node

双端的模块化: 浏览器 + Node.js

通过module.exports将模块进行导出,暴露出模块接口,通过require引入模块,实现模块的导入。commonJS是同步执行的,因为涉及到的文件方法缓存在本地磁盘中因此读取时不会发生阻碍,同步执行不会产生代码的拥堵现象。

说明:

  1. 每一个文件都可以当作一个模块
  2. 在服务器端: 模块的加载时是运行时同步加载的
  3. 在浏览器端: 模块需要提前编译打包处理

2009年,美国程序员Ryan Dahl创造了node.js项目,将javascript语言用于服务器端编程。 这标志"Javascript模块化编程"正式诞生。因为老实说,在浏览器环境下,没有模块也不是特别大的问题,毕竟网页程序的复杂性有限; 但是在服务器端,一定要有模块,与操作系统和其他应用程序互动,否则根本没法编程。

暴露 与 引入

暴露模块

module.exports = value;

exports.xxx = value;

引入模块

require()

暴露的本质: module.export 所指向的对象

1. 安装Node.js

2. 创建项目结构

|-modules
|-module1.js
|-module2.js
|-module3.js
|-app.js
|-package.json
{
"name": "test-0719",
"version": "1.0.0"
}

3. 模块化编码:

  • module1.js

    module.exports = {
    data:'module1',
    foo(){
    console.log('foo()------',this.data);
    },
    bar(){
    console.log('bar()------',this.data);
    }
    }
  • module2.js

    module.exports = function () {
    console.log('module2');
    }
  • module3.js

    exports.foo = function () {
    console.log('foo() module3');
    }
    js
    exports.bar = function () {
    console.log('bar() module3');
    }
  • app.js

    let module1 = require('./modules/module1')
    let module2 = require('./modules/module2')
    let module3 = require('./modules/module3')
    let a = require('uniq')
    module1.foo()
    module1.bar()
    module2()
    module3.foo()
    module3.bar()
    let arr = [1,11,2,2,2,5,5,5,3,4,6,6,9,7,8]
    console.log(a(arr));

4. 在node环境下运行app.js:

  • :用命令启动: node app.js

浏览器端

CommonJS-Browserify

1. 创建项目结构

|-jsBrowserify
|-dist //生成编译完js的目录
|-src //源码所在的目录(我们编写的、没经过工具处理的代码,叫做源码)
|-module1.js
|-module2.js
|-module3.js
|-app.js
|-index.html
|-package.json
{
"name": "test-0719",
"version": "1.0.0"
}

2. 模块化编码

  • module1.js

    module.exports = {
    foo() {
    console.log('moudle1 foo()')
    }
    }
  • module2.js

    module.exports = function () {
    console.log('module2()')
    }
  • module3.js

    exports.foo = function () {
    console.log('module3 foo()')
    }
    exports.bar = function () {
    console.log('module3 bar()')
    }
  • 下载第三方模块uniq:打开左下角的Terminal,cd到02_CommonJS-Node路径,输入命令:npm install uniq --save

  • app.js

    //引用模块
    let module1 = require('./module1')
    let module2 = require('./module2')
    let module3 = require('./module3')
    let uniq = require('uniq')
    //使用模块
    module1.foo()
    module2()
    module3.foo()
    module3.bar()
    console.log(uniq([1, 3, 1, 4, 3]))

3. 下载browserify(用于把CommonJS的模块化语法,翻译成浏览器认识的语法,是一个“翻译官”)

  • 全局安装browserify,命令: npm install browserify -g

4. 执行处理命令

  • 第一步,cd到指定文件夹(03_CommonJS-Browserify)即:app.js所在的文件夹
  • 第二步,输入命令browserify js/src/app.js -o js/dist/bundle.js

5. 页面使用引入:

<script type="text/javascript" src="js/dist/bundle.js"></script>

AMD-RequireJs

AsynchronousMoule Definition 异步模块化定义

专门用于浏览器端, 模块的加载是异步的

requireJS 的核心原理是什么?

(如何动态加载的?如何避免多次加载的?如何 缓存的?)

requireJS的核心是通过动态创建script标签的src来引入模块,同时对每个脚本的load事件进行监听,如果每个脚本都加载完成了再执行回调函数。

定义暴露模块

define(function(){
return
})
  1. 下载require.js
  1. 创建项目结构
    |-js
    |-libs
    |-require.js
    |-modules
    |-loger.js
    |-dataService.js
    |-main.js
    |-index.html
  2. 定义require.js的模块代码
  • dataService.js

    define(function () {
    let msg = 'atguigu.com'
    function getMsg() {
    return msg.toUpperCase()
    }
    return {getMsg}
    })
  • loger.js

    define(['dataService', 'jquery'], function (dataService, $) {
    let name = 'Tom2'
    function showMsg() {
    $('body').css('background', 'gray')
    console.log(dataService.getMsg() + ', ' + name)
    }
    return {showMsg}
    })
  1. 应用主(入口)js: main.js

    requirejs.config({
    baseUrl: '', 如果配置了baseUrl,那么项目的根目录就是index.html所在目录
    //模块标识名与模块路径映射
    paths: {
    "loger": "modules/loger",
    "dataService": "modules/dataService",
    }
    })
    //引入使用模块
    requirejs( ['loger'], function(loger) {
    loger.showMsg()
    })
  2. 页面使用模块:

主页面中也要特殊的引入方式
<script data-main="js/main.js" src="js/libs/require.js"></script>

​

  1. 使用第三方基于require.js的框架(jquery)
  • 将jquery的库文件导入到项目:

    • js/libs/jquery-1.10.1.js
  • 在main.js中配置jquery路径

    paths: {
    'jquery': 'libs/jquery-1.10.1'
    }
  • 在loger.js中使用jquery

    define(['dataService','jquery'],function (dataService,$) {
    function showMsg() {
    console.log(dataService.getData());
    $('body').css('background','skyblue')
    }
    return {showMsg}
    })
  • 备注:define中的要写jquery不可以写jQuery,因为jQuery源码已经对AMD模块化进行了适配,已经定义好了"jquery"

CMD SeaJs

  1. 下载sea.js, 并引入
  1. 创建项目结构
    |-js
    |-libs
    |-sea.js
    |-modules
    |-module1.js
    |-module2.js
    |-module3.js
    |-module4.js
    |-main.js
    |-index.html
  2. 定义sea.js的模块代码
  • module1.js

    define(function (require,exports,module) {
    var name = 'module1';
    function fun1() {
    console.log(name);
    }
    //暴露模块
    exports.showName = fun1
    });
  • module2.js

    define(function (require,exports,module) {
    var name = 'module2';
    function fun2() {
    console.log(name);
    }
    //暴露模块
    module.exports = fun2
    });
  • module3.js

    define(function (require,exports,module) {
    var name = 'module3';
    function fun3() {
    console.log(name);
    }
    //暴露模块
    module.exports = fun3
    });
  • module4.js

    //module4依赖于module2,module3
    define(function (require,exports,module) {
    var name = 'module4';
    function fun4() {
    console.log(name);
    }
    //[同步]引入module2
    let module2 = require('./module2')
    module2()
    //[异步]引入module3
    require.async('./module3',function (m3) {
    m3.foo()
    })
    //暴露模块
    module.exports = fun4
    });
  • main.js : 主(入口)模块

    define(function (require) {
    var m1 = require('./module1')
    var m4 = require('./module4')
    m1()
    m4()
    })
  1. index.html:
    <!--
    使用seajs:
    1. 引入sea.js库
    2. 如何定义导出模块 :
    define()
    exports
    module.exports
    3. 如何依赖模块:
    require()
    4. 如何使用模块:
    seajs.use()
    -->
    <script type="text/javascript" src="js/libs/sea.js"></script>
    <script type="text/javascript">
    seajs.use('./js/modules/main')
    </script>
    5.思考:为什么运行后输出结果如下?
module2
module1
module4
module3

ES6_Bable

说明:

依赖模块需要编译打包处理

暴露模块-export

  1. 分别暴露: export 暴露内容
  2. 统一暴露: export {bula..., bula...}
  3. 默认暴露: export default 暴露内容 (只能暴露一次)

引入模块-import

  1. import {bula..., bula...} from './module1'
  2. import moudle3 from '',.module3

在Es6 模块化中 用哪一种方式暴露 就用对应的引入

1. 创建项目结构

|-js
|-src
|-module1.js
|-module2.js
|-module3.js
|-app.js
|-index.html
|-package.json
{
"name" : "es6-modular-0719",
"version" : "1.0.0"
}

2. 安装babel-cli, babel-preset-es2015和browserify:

第一步,全局安装:npm install babel-cli browserify -g 第二步,局部安装:npm install babel-preset-es2015

cli -> command line Interface 命令行接口工具

bablerc = run control

3. 创建.babelrc文件(给babel指定具体的任务),内容如下:

{
"presets": ["es2015"]
}

4. 编码

  • js/src/module1.js

    //分别暴露
    export function foo() {
    console.log('module1 foo()');
    }
    export function bar() {
    console.log('module1 bar()');
    }
    export const DATA_ARR = [1, 3, 5, 1]
  • js/src/module2.js

    //统一暴露
    let data = 'module2 data'
    function fun1() {
    console.log('module2 fun1() ' + data);
    }
    function fun2() {
    console.log('module2 fun2() ' + data);
    }
    export {fun1, fun2}
  • js/src/module3.js

    //默认暴露
    export default {
    name: 'Tom',
    setName: function (name) {
    this.name = name
    }
    }
  • 下载jQuery模块: npm install jquery --save

  • js/src/app.js

    import {foo, bar} from './module1'
    import {DATA_ARR} from './module1'
    import {fun1, fun2} from './module2'
    import person from './module3'
    import $ from 'jquery'
    $('body').css('background', 'red')
    foo()
    bar()
    console.log(DATA_ARR);
    fun1()
    fun2()
    person.setName('JACK')
    console.log(person.name);

5. 编译源代码(确保已进入 ES6_Babel_Browserify所在文件夹)

  • 第一步:使用Babel将ES6编译为ES5代码 (无require) 命令为: babel js/src -d js/build
  • 第二步:使用Browserify编译js上一步生成的js 命令为: browserify js/build/app.js -o js/build/build.js
  • 备注:第一步操作后Babel将es6的模块化语法,转换成了CommonJS模块化语法(浏览器不识别),所以需要第二步用Browserify再次编译。

6. 页面中引入测试

<script type="text/javascript" src="js/build/build.js"></script>

ES6 模块与 CommonJS 模块、AMD、CMD 的差异。

CommonJS输出的是一个值的拷贝,而ES6输出的是值的引用。

CommonJS正因为输出的是值的拷贝,所以模块在进行输出后,若模块内部发生改变便影响不到这个值,需对其重新拷贝。ES6的运行机制和CommonJS不同,js引擎遇到模块加载命令import时会生成一个只读引用,当脚本真正执行时,再根据这个只读引用到模块中去加载。

CommonJS是运行时加载,ES6是编译时输出接口,CommonJS输出的是整个对象,它将模块看成是一个对象,当需要某个方法时就到该对象中去查找。ES6是编译时输出一个静态接口,在代码静态解析时就会生成。

AMD 和 CMD 规范的区别?

异步模块定义(AMD)是Asynchronous Module Definition的缩写,是 RequireJS 在推广过程中对模块定义的规范化产出。 通用模块定义(CMD)是Common Module Definition的缩写,是SeaJS 在推广过程中对模块定义的规范化产出。