supporting both CommonJS and AMD

后端 未结 6 2273
臣服心动
臣服心动 2020-11-29 18:15

Is there a way to create a javascript micro-library (a library that has no dependencies), that support all of the following module formats:

  • Asynchronous Module
6条回答
  •  余生分开走
    2020-11-29 19:10

    This is based on Nijikokun's answer. Since RequireJS discourages the use of explicit module names this has been omitted in this version. The second argument to the loader describe the dependencies. Pass [] if you don't need to load any.

    var loader = function(name, dependencies, definition) {
      if (typeof module === 'object' && module && module.exports) {
          dependencies = dependencies.map(require);
          module.exports = definition.apply(context, dependencies);
      } else if (typeof require === 'function') {
        define(dependencies, definition);
      } else {
        window[name] = definition();
      }
    };
    
    loader('app', ['jquery', 'moment'], function($, moment) {
       // do your thing
       return something;
    }
    

提交回复
热议问题