Search code examples
node.jsnpmwebpackamdcommonjs

How to fetch modules from npm as standalone AMD/CommonJS modules


So, I'm not using Node or WebPack serverside, but would still like to use modules from npm every now and then. My clientside uses requirejs, so I would need the modules in either AMD (preferred) or CommonJS.

What I want to archieve is a script that takes the module name + "external dependencies" as arguments and creates a module that contains all the other deps.

E.g.

sh npmtoamd.sh draft-js react react-dom

It creates an ES5 AMD module that contains draft-js and all of it's dependencies excluding react and react-dom. If it's not possible to eg. include css files and other non-js content in the module, providing them in eg. draft-js.css is tolerable.

While I don't use Node or Webpack serverside, we can use npm and webpack in the said script.

Fetching the module from npm is the trivial part, but I'm pretty lost in how to do the webpack parts. I know for a fact that it's possible though, as I managed to do it earlier with help, just don't have it down anywhere and no idea how it went.


Solution

  • I ended up doing the npm fetch thingy in java instead of a batch script and finally got it working. Didn't get browserify to work however.

    Heres what I do:

    1. creating the following webpack.config.js

      module.exports = {
          entry: './main.js',
          output: {
          filename: 'bundle.js',
          library:"<modulename>",
          libraryTarget:"amd"       
      },
      externals: {
      
              react: "React",
          "react-dom": "ReactDOM",
          immutable:"Immutable",
          moment:"Moment"
          }   
      
      };
      
    2. npm install <modulename>

    3. Creating the following main.js

      define('FOOBAR', ['<modulename>'], function(Foo) {
         return Foo;
      });
      
    4. Running webpack main.js