夜猫的小站

umd示例代码

Published on
阅读时间:3分钟488

本文最近一次更新于 1504 个天前,其中的内容很可能已经有所发展或是发生改变。

前言

umd是一种兼容浏览器和node环境的模块引用方案,是一种同时兼容commonjs以及AMD的方案。

示例代码

umd顶部一般都会有如下代码,用来判断代码执行环境

// Uses AMD or browser globals to create a module.

// If you want something that will also work in Node, see returnExports.js
// If you want to support other stricter CommonJS environments,
// or if you need to create a circular dependency, see commonJsStrict.js

// Defines a module "amdWeb" that depends on another module called "b".
// Note that the name of the module is implied by the file name. It is best
// if the file name and the exported global have matching names.

// If the 'b' module also uses this type of boilerplate, then
// in the browser, it will create a global .b that is used below.

// If you do not want to support the browser global path, then you
// can remove the `root` use and the passing of `this` as the first arg to
// the top function.

(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(['b'], factory);
    } else if (typeof exports === 'object') {
        // CommonJS 兼容node环境
        var $ = require('jquery');
        module.exports = factory($);
    } else {
        // Browser globals
        root.amdWeb = factory(root.b);
    }
}(typeof self !== 'undefined' ? self : this, function (b) {
    // Use b in some fashion.

    // Just return a value to define the module export.
    // This example returns an object, but the module
    // can return a function as the exported value.
    return {};
}));

其他

  • commonjs

CommonJS 加载的是一个对象(即module.exports属性),该对象只有在脚本运行完才会生成。而 ES6 模块不是对象,它的对外接口只是一种静态定义,在代码静态解析阶段就会生成。

  • es modules

Es6模块不是一个对象,而是通过export显式指定输出的代码,import时采用静态命令的形式,就是可以指定加载某一个输出值,而不是加载整个模块。