Search code examples
javascriptnode.jsbrowserifyamdumd

How to convert my CommonJS module to UMD?


I'm new to UMD and AMD. I've written a JS library in Browserify and I've just came across UMD. My understanding is if I include a piece of code for every module, my module should be able to be used in CommonJs and AMD.

Here's my sample Module.

./src/main.js

import Cookie from 'js-cookie'; // from npm install js-cookie
import lib1 from './lib/lib1';

window.MyModule = function MyModule(options) {
  let lib1;
  function methodA() {

  }

  return {
    methodA: methodA
  };

  (function init() {
    lib1 = lib1();
    // Some initialization code.
  })();
};

module.exports = window.MyModule;

./lib/lib1.js

module.exports = (options) => {
  function func1() {

  }

  return {
    func1: func1
  };
}

And this is how I pack everything using browserify

browserify src/main.js --outfile dist/main.js --debug

And when I want to use this module I just do.

<script src="//main.js"></script>

My question is, how do I convert my module to be UMD so it can be included in both CommonJS and AMD.


Solution

  • You can use deamdify, es6ify and deglobalify to do what you're after.

    npm install deamdify es6ify deglobalify
    browserify -t deamdify -t es6ify -t deglobalify main.js -o bundle.js
    

    Source: http://dontkry.com/posts/code/browserify-and-the-universal-module-definition.html