Compile an npm module into a single file, without dependencies

Prajjwal picture Prajjwal · Mar 28, 2014 · Viewed 11.7k times · Source

I'm trying to compile an the uncss npm module into a single .js file that is suitable for compilation by ExecJS. For example, the coffee script guy has this. The goal is to create a simple ruby wrapper for it, similar to ruby-coffee-script.

What I have tried to far:

  1. Came across an answer that suggested UglifyJS. Got nowhere with it.
  2. Used browserify, which should have done the trick, but it fails to compile lib/uncss.js with the following error message:

    Error: ENOENT, open 'tls' while resolving "tls" from file /home/prajjwal/code/uncss/node_modules/request/node_modules/forever-agent/index.js
    

I suppose this is because browserify does not have a proper shim for it? I'm also concerned about the shims that browserify replaces node modules with. Are they completely safe to use? I'm going to be embedding this into a ruby gem. Don't think browserify is what I should be using. Is there another way I can generate a stand alone .js from an npm module?

Any help appreciated.

Answer

xer0x picture xer0x · Nov 16, 2014

Browserify has a --standalone flag that can help here.

On the command line:

browserify -s moduleName --bare moduleName.js -o filename.js

In your node script you can import the concatenated module normally:

var moduleName = require('./filename');

However, you will may still need to ignore and/or stub out any tricky modules.