Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

supporting both CommonJS and AMD

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 Definition
  • CommonJS
  • exposing the library's exports as a global namespace object (no loader)
like image 453
slobo Avatar asked Dec 02 '12 20:12

slobo


People also ask

What is CommonJS and AMD?

AMD and CommonJS are both Javascript module loader. They accomplish the same task but works different. AMD is better for browser, hence, the name 'Asynchronous', as it loads each distinct module in async manner instead of loading in one large file. No extra steps are required to use AMD, it works out-of-the-box.

What is AMD CommonJS and UMD?

Alright, I understand. cjs (commonJS) is the module system used by e.g. Node, and umd (Universal Module Definition) is the type of modules that strive to work everywhere. If you want to include any of these files in the browser as standalone script tags without a build step like e.g. Webpack, you will want to use umd.

Can I import CommonJS module?

CommonJS modules cannot import ES Modules. You are not able to import . mjs files from . js files. This is due to the different nature of the two systems.


1 Answers

Yes, and I owe this answer to ded and his awesome modules:

(function(name, definition) {     if (typeof module != 'undefined') module.exports = definition();     else if (typeof define == 'function' && typeof define.amd == 'object') define(definition);     else this[name] = definition(); }('mod', function() {     //This is the code you would normally have inside define() or add to module.exports     return {         sayHi: function(name) {             console.log('Hi ' + name + '!');         }     }; })); 

This can then be used:

  1. in AMD (e.g. with requireJS):

    requirejs(['mod'], function(mod) {     mod.sayHi('Marc'); }); 
  2. in commonJS (e.g. nodeJS):

    var mod = require('./mod'); mod.sayHi('Marc'); 
  3. globally (e.g. in HTML):

    <script src="mod.js"></script> <script>mod.sayHi('Marc');</script> 

This method needs to get more publicity - if jQuery and co. started using it life would be much easier!

like image 150
Marc Avatar answered Oct 05 '22 14:10

Marc