js 模块化总结

目前主流的模块化框架有 commonJS / amd / cmd / umd / es module ,动态引用时使用 es 比较好;

模块示例代码:

umd

模块声明:

(function (name, context, factory) {
    if (typeof module === 'object' && typeof module.exports === 'object') {
        console.log("function in object ");
        module.exports = factory();
    } else if (typeof window.define === 'function' && window.define.amd) {
        console.log("function in define.amd ");
        window.define(factory);
    }
    else if (typeof exports === "object") {
        console.log("function in context.exports ");
        context.exports = factory();
    }
    else {
        console.log("function in context[name] " + context);
        context[name] = factory();
    }
}("test2", this, function () {
    console.log("function body " + this);
    function SDK() {
        this.call1 = function () {
            console.log("call1 in .");
        }
        this.call2 = function () {
            console.log("call2 in .");
        }
    }
    const sdk = new SDK();
    console.log("function body out " + this);
    return sdk;
}));

模块调用:

import('./test2.js').then((test2) => {
    console.log("test22 in . ");
    test2.SDK().call1();
    console.log("test22 out. ");
})

es module

方法声明:
function SDK() {
    function SDK() {
        this.getData = function() {
            console.log("getData in.");
        }
    }
    const msdk = new SDK();
    return msdk;
}

export function getData() {
    new SDK().getData();
}

方法调用1:
import('./test2.js').then((test2) => {
    console.log("test22 in . ");
    test2.getData();
    console.log("test22 out. ");
})
方法调用2:
import {getData} from './test2.js'

var data = getData();

commomJS

导出
var a = 1;
function b() {}

module.exports {a:a, b:function()}

引用:
var b = require('./test.js');
b();

amd

define('myModule', 
    ['foo', 'bar'], 
    function ( foo, bar ) {
        var myModule = {
            doStuff:function(){
                console.log('Yay! Stuff');
            }
        }
        return myModule;
});

require(['foo', 'bar'], function ( foo, bar ) {
        // 这里写其余的代码
        foo.doSomething();
});

ESM 是最好的模块格管理式,这要归功于其简单的语法、异步性质和 tree-shakeability。
UMD 随处可用,通常用作 ESM 不起作用时的后备方案
CJS 是同步的,有利于后端。
AMD 是异步的,适合前端。

https://juejin.cn/post/6895952580607016968
es6 学习
https://www.w3cschool.cn/escript6/escript6-v8gr37fg.html

你可能感兴趣的:(js 模块化总结)