1.模块化

模块化发展:

1.命名空间

库名.类别名.方法名: 

var NameSpace = {};

NameSpace.type = NameSpace.type || {};

NameSpace.type.method = function () {};

--------------------------------------------------------------

代码示例

var MYAPP = MYAPP || {};

        MYAPP.namespace = function (ns_string) {

            var parts = ns_string.split('.'),

                parent = MYAPP,

                i;

            // strip redundant leading global

            if (parts[0] === "MYAPP") {

                parts = parts.slice(1);

            }

            for (i = 0; i < parts.length; i += 1) {

                // create a property if it doesn't exist

                if (typeof parent[parts[i]] === "undefined") {

                    parent[parts[i]] = {};

                }

                parent = parent[parts[i]];

            }

            return parent;

        };

缺点: 

如果命名空间被覆盖很难检测到;

必须要记住完整路径名,比较麻烦;

2.commonJS

Modules/1.1.1

    一个文件为一个模块

通过module.exports暴露模块接口

通过require 引入模块

同步执行

http://wiki.commonjs.org/wiki/Modules/1.1.1

代码示例:

var EventEmitter = require('events').EventEmitter;

var mixin = require('merge-descripotors');

var proto = require('./application');

var Route = require('./router/router');

var req = require('./request');

var res = require('./response');

/**

* Expose 'carateApplication()'

*/

exports = module.exports = createApplication;


3.AMD  (Asynchronous Module Definition)

特点:前置执行

代码示例:

define([

    'alpha',      //'require',

    ['require', 'exports', 'beta']      //'dependency'

], function(require, exports, beta) {    // require, factory 模块输出

    'use strict';

    exports.verb = function () {

    return beta.verb();

    // or:

    return require('beta').verb();

}

});


4.CMD (Common Module Definition)

一个文件为一个模块;

使用define来定义一个模块;

使用require来加载一个模块;

尽可能懒执行。

代表作: SeaJS;

https://github.com/cmd.js/specification/blob/master/draft/module.md

代码示例: 

//所有模块通过 define 来定义

define(function (require, exports, module) {

    //通过 require 引入依赖

    var $ = require('jquery');

    var Spinning = require('./spinning');

    //通过 exports 对外提供接口

    exports.doSomething = ...

    //或者通过 module.exports 提供整个接口

    module.exports = ...

})


5.UMD (Universal Modele Definition)

通用解决方案

三个步骤:

    判断是否支持AMD;

    判断是否支持CommonJS;

    如果都不支持,则定义为全局变量。

代码示例:


6. ES 6 module

一个文件为一个模块

export/ import

代码示例:

// Default exports and named exports

import theDefault, { named1, named2 } from 'src/mylib';

import theDefault from 'src/mylib';

import { named1, named2 } from 'src/mylib';

//Renaming: import named1 as myNamed1

import { named1 as myNamed1, named2 } from 'src/mylib';

//Importing the module as an object

// (with one property per named export)

import * as mylib from 'src/mylib';

//Only load the module, don't import anything

import 'src/mylib';


webpack支持:

AMD(requireJS)

ES Modules(recommend)

CommonJS

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容