How to expose an es6 module globally

|▌冷眼眸甩不掉的悲伤 提交于 2020-01-02 01:37:10

问题


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.


回答1:


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.




回答2:


This is basically the same issue as Exporting a class with Webpack and Babel not working , except that you have a named export instead of a default export. Your entry file should be

import {MyMod} from './mymod';
module.exports = MyMod;

or

module.exports = require('./mymod').MyMod;

If you don't want to do any of these and keep './src/mymod.js' as entry file, use a CommonJS export instead of an ES6 export in that file:

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


来源:https://stackoverflow.com/questions/38954794/how-to-expose-an-es6-module-globally

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!