Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to expose an es6 module globally

I need to write a module that will be available on the window global.
I'm using es6 to create the module and every single class I define has it's own file.
I'm using webpack to babelify and bundle these classes.
The entry point of my module is also the file containing the global to be exposed.

I've tried every method to make this possibe, icluding:

  • expose-loader
  • import-loader
  • expoert-loader
  • output: library
  • black-magic :(

Example of code I've tried:

I want to get: window.MyMod

// mymod.js
export class MyMod {
    constructor(aaa) {
        this.aaa = aaa;
    }
    toString() {
        return this.aaa;
    }
}

// webpack.config
var entries = [
    './src/mymod.js'
];
module.exports = {
    ...,
    module: {
      loaders: [
            {
                test: require.resolve('./src/mymod.js'),
                loader: 'expose?MyMod'
            },
            {
                test: /\.js$/,
                exclude: /node_modules/,
                loader: 'babel-loader',
                query: {
                    presets: ['es2015']
                }
            }
    ]
}

This only gets me an object MyMod on the window that contains MyMod as a constructor.

Any help will be appreciated.

like image 871
bldoron Avatar asked Aug 15 '16 12:08

bldoron


1 Answers

You should combine export default class Foo with the library and libraryTarget settings in Webpack's config. Something like:

// src/Foo.js
export default class Foo { ... }

// webpack.config.json
{
  "output": {
    "library": "Foo",
    "libraryTarget": "var"
  }
}

You should be able to use the library as window.Foo once the bundle has been loaded.

like image 166
ssube Avatar answered Nov 15 '22 21:11

ssube