Search code examples
node.jsnpmbrowserify

Browserify a library rather than a file


I am tryng to use npm libraries in browsers. Taking the npm library uniq as an example, at the moment, we need first to write locally the code that uses uniq:

// main.js
var unique = require('uniq');    
var data = [1, 2, 2, 3, 4, 5, 5, 5, 6];
console.log(unique(data));

Then, we need to run browserify in a console:

browserify main.js -o bundle.js

Now, we could use it in a html file:

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

My question is, whether it is possible to browserify a library such that any code inside the "script" tag could use it. For example, in the html part, I may want to write

<html>
  <head>
    <script src="the_browserified_library.js"></script>
  </head>
  <body>
    <script>
       <!-- the following code may change -->
       var d = [1, 1, 2, 3];
       console.log(unique(d));
       var a = [2, 2, 4, 5];
       console.log(unique(a));
    </script>
  </body>
</html>

If it is possible, we will not have to browserify (in a console) the code each time after changing it.

Does anyone know if it is possible by browserify or any other tools?

Edit 1: following the answer of @dNitro, I installed globalify globally, but later it gives an error:

/tmp/client$ globalify uniq -o uniq.js
/usr/local/lib/node_modules/globalify/node_modules/camelcase/index.js:4
    let isLastCharLower = false;
    ^^^
SyntaxError: Unexpected strict mode reserved word
    at exports.runInThisContext (vm.js:73:16)
    at Module._compile (module.js:443:25)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at Object.<anonymous> (/usr/local/lib/node_modules/globalify/globalify.js:7:17)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)

Solution

  • So you want make global variable of a npm package?! Use globalify:

    installation:

    npm install globalify -g
    

    Usage:

    globalify uniq -o uniq.js
    

    then in your html:

    <script src="uniq.js"></script>    
    <script>
      var d = [1, 1, 2, 3];
      console.log(uniq(d));
    </script>
    

    Note that you should avoid polluting global scope. writing code this way is harmful. browserify not only make your code browser ready, it helps you write clean (doesn't pollute global window scope), modular (the CommonJS or ES6 way) and future proof (write ES6 and transpile it on bundle time) and your app is ready with just one http request to bundle.js file.

    If running browserify everytime you change your code, bothers you, you could consider using watchify; It automatically rebuild the bundle on every change you made in your files.