Will Luce
Will Luce

Reputation: 1841

Compile NPM package with Browserify

I need to use the functionality of an NPM package (fit-file-parser) in a non-Node app. So far, I've tried

  1. Pull down the package, build it, and include the output bundle as a script tag. The problem here is that the built package dist/ includes 4 files, each of which is using modules via require(). Mostly, they depend on one another so I thought I could just include them in the correct order, but one depends on buffer.
binary.js
fit-parser.js
fit.js
messages.js
  1. Run the dist/ directory through Browserify to produce a package.bundle.js file and include that as a script tag. This seems to run without error, but the main function I need to instantiate the logic I need isn't present in the browser. Actually, none of the globals present when running the files directly are present after including the bundle file.
browserify fit-parser.js -o fit-parser.bundle.js

To use this package, one needs to be able to instantiate a new FitParser using new FitParser({...options}). This function comes from the fit-parser file, but I can't seem to get it into the global scope of the browser.

Upvotes: 0

Views: 3482

Answers (1)

Keith
Keith

Reputation: 24181

NPM packages are generally modules, as such they don't normally effect the global.

Normally you would be doing something like ->

const FitParser = require("fit-parser");

or

import {FitParser} from "fit-parser"

The second option is now supported in modern browsers, so in theory you could use that option and not use browserfy.

But if you want to use the old fashioned way, with a global. This is what --standalone {exportname} option is used for. {exportname} been what you want to call it on the global. Basically it's kind of doing a window.FitParser = FitParser inside the script.

Upvotes: 3

Related Questions