Shubham Kanodia
Shubham Kanodia

Reputation: 6236

How to compile a npm module into a browser script?

I want to customize the Parse SDK. They provide source through an npm module, which makes it usable in node environments.

How can I compile this node module into a standalone parse.js script which will run as it is on a browser?

I tried using browserify as

browserify ./parse -o parse.js

but the parse.js it spits out is quite large and still contains node remanents: process and require commands. Although it executes without any error on browser, the browser cannot find Parse definition.

Upvotes: 1

Views: 1247

Answers (2)

Shubham Kanodia
Shubham Kanodia

Reputation: 6236

Found the correct way to compile the parse npm module into a browser script is to use:

browserify path/to/npm/parse --standalone parse > parse-browser.js

For any other script it should be :

browserify path_to_module --standalone global_name_to_expose > output.js

Also, since the parse node module has a lot of node code, I would recommend people to use envify followed by uglify to make their code more optimized.

Upvotes: 3

Pete TNT
Pete TNT

Reputation: 8403

AFAIK, Parse-module doesn't expose itself as a browser global. You should have a file, such as app.js that contains your definitions and use that to require the Parse module.

For example:

//app.js
var Parse = require("parse");
console.log(Parse)

Bundle it (the bundle will contain your app.js and the contents of the parse-module:

browserify ./app.js -o app.bundle.js

and include the bundled file to your HTML file

<script src="app.bundle.js"

After you open your HTML file, you should see the Parse object in your console.

Upvotes: 0

Related Questions