Search code examples
javascriptgulpecmascript-6browserify

Browserify standalone option doesn't directly wraps the code with specified name?


I tried to use gulp, browserify, watchify, and babelify to compile a standalone js module. The options is like this:

const browserifyOpts = {
  debug: true,
  entries: path.join('src', 'index.js'),
  standalone: 'Goo',
  transform: [
    'babelify',
  ],
};

My JS module is as follows:

export default class Goo {
  constructor() {
    this.a = 'hello';
  }
}

It compiles fine. But when I include it in a script tag in a html file, the Goo module is wrapped inside window.Goo.default, that is, I cannot directly use:

new Goo();

but have to use:

new Goo.default();

Any idea where went wrong? Thanks!


Solution

  • The easiest option would be to wrap this yourself by having your index.js file contain something like

    module.exports = require('./main').default;
    

    and move your current index.js to main.js. Then you'll be set.

    As the other answer says, you can potentially use babel-plugin-add-module-exports, but that is not something I'd generally recommend because while it fixes this problem, it also introduces the possibility that you could accidentally write import/export pairs that work but are not spec-compliant.