在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問(wèn)答/HTML5  嵌入式  HTML/ 關(guān)于javascript插件源碼的問(wèn)題?

關(guān)于javascript插件源碼的問(wèn)題?

很多js插件源碼都有如下代碼:

//兼容CommonJs規(guī)范
if (typeof module !== 'undefined' && module.exports) module.exports = MyPlugin;

//兼容AMD/CMD規(guī)范
if (typeof define === 'function') define(function() { return MyPlugin; });

這兩段代碼具體作用是什么呢?
對(duì)于提高原生插件的編寫能力有沒(méi)有相關(guān)方面的書籍可以看呢?

回答
編輯回答
悶油瓶

這些基本都是模塊化方案,實(shí)際上自己頁(yè)很容易寫出模塊化的原理
webpack

(function(modulesArr) {
    var rootModule = {};
    function __require__(id) {
        if (rootModule[id]) {
            return rootModule[id].exports;
        }
        var currentModule = modulesArr[id];
        var module = {
            id,
            exports: {}
        };
        currentModule.call(module.exports, module.exports, module, __require__);
        currentModule[id] = module;
        return module.exports;
    }
    return __require__(0);
})([
    function(exports, module, require) {
        var m1 = require(1);
        console.log(m1);
    },
    function(exports, module, require) {
        exports.msg = 'Hello World';
        var m2 = require(2);
        m2();
    },
    function(exports, module, require) {
        module.exports = function() {
            var str = 'Hello World';
            console.log(str);
            return str;
        };
    }
]);

我自己實(shí)現(xiàn)的browser端模塊化

(function(global) {
    'use strict';
    var errMsg = Math.random().toString(32).substr(2);
    var rootModule = {};
    function ModuleCtor(id) {
        if (!this || this.__proto__ !== ModuleCtor.prototype) {
            return new ModuleCtor(id);
        }
        this.id = id;
        this.exports = {};
        this.loaded = !1;
    }

    function define(id, fn) {
        if (typeof id === 'function') {
            fn = id;
            id = document.currentScript
                ? document.currentScript.src
                : Math.random()
                      .toString(32)
                      .substr(2);
        }
        if (typeof id !== 'string') {
            id = '' + id;
        }
        var module = ModuleCtor(id);
        exec();
        function __require__(src) {
            if (rootModule[src] && rootModule[src].__proto__ === ModuleCtor.prototype) {
                return rootModule[src].exports;
            }
            loadScript(src, function() {
                exec();
            });
            throw new Error(errMsg);
        }
        function exec() {
            try {
                fn.call(module.exports, module.exports, module, __require__);
                module.loaded = !0;
                rootModule[id] = module;
            } catch (err) {
                if (err.message !== errMsg) {
                    throw err;
                }
            }
        }
    }

    function loadScript(src, callback) {
        var script = document.createElement('script');
        script.src = src;
        script.onload = function() {
            callback && callback(src);
        };
        document.body.appendChild(script);
        return script;
    }
    global.define = define;
})(window);

本質(zhì)都是js沒(méi)有模塊,所以我們就想到全局暴露一個(gè)rootModule對(duì)象,每一個(gè)鍵都是一個(gè)模塊,exports對(duì)象是依賴的暴露。
如a.js

    module.exports = 'Hello World';

b.js

    var chars = require('./a');
    process.stdout.write(chars + '\n'); // Hello World

但是我們?cè)趺磳?shí)現(xiàn)呢,(一)編譯:如webpack,(二)暴露一個(gè)函數(shù),如requirejs、seajs。


webpack 可以配置 output libraryTarget: 'umd', library: 'globalVarName' 打題主說(shuō)的這種umd包,兼容瀏覽器,requirejs,node環(huán)境。


另外我還是忍不住吐槽一下seajs的垃圾,一個(gè)文件的多個(gè)require發(fā)請(qǐng)求時(shí)沒(méi)有順序之分,字符串正則來(lái)分析依賴。。。如果jQuery的plugin依賴jQuery,需要對(duì)jQueryplugin改一下代碼討個(gè)套個(gè)客,不能直接想requirejs直接在config中聲明依賴。垃圾。當(dāng)然我自己寫的模塊加載更垃圾,連依賴都不分析。多try幾次必然成功。

2018年8月3日 08:20
編輯回答
未命名

都是模塊化方案。

amd 對(duì)應(yīng) requireJs
cmd 對(duì)應(yīng) seaJs
commonJs 對(duì)應(yīng) nodeJs

之所以都想兼容過(guò)去,是因?yàn)楹芏鄇s文件可以兼容運(yùn)行在瀏覽器和node環(huán)境,為了重復(fù)利用,加上你列出的通用代碼,是最合適不過(guò)的,比如一個(gè)字符串處理trim,那么就可以在node和browser同時(shí)使用。不加模塊化代碼的話,就可能得寫3份重復(fù)的js了。

2017年10月11日 06:44