简体   繁体   English

如何全局公开es6模块

[英]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. 我正在使用es6来创建模块,我定义的每个类都有自己的文件。
I'm using webpack to babelify and bundle these classes. 我正在使用webpack来babelify并捆绑这些类。
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 expoert装载机
  • output: library 输出:库
  • black-magic :( 黑魔法 :(

Example of code I've tried: 我试过的代码示例:

I want to get: window.MyMod 我想得到: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. 这只会让我在包含MyMod作为构造函数的窗口上找到一个MyMod对象。

Any help will be appreciated. 任何帮助将不胜感激。

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. 与使用Webpack和Babel导出类不起作用基本相同,除了您有一个命名导出而不是默认导出。 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: 如果您不想执行任何这些操作并将'./src/mymod.js'保留为条目文件,请在该文件中使用CommonJS导出而不是ES6导出:

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

You should combine export default class Foo with the library and libraryTarget settings in Webpack's config. 您应该将export default class FoolibraryTarget配置中的librarylibraryTarget设置组合在一起。 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. 一旦加载了包,您应该能够将库用作window.Foo

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM