Webpack 4 - 将变量暴露给全局上下文

时间:2018-03-18 17:47:35

标签: javascript web webpack ecmascript-6 bundler

我正在ES6中编写一个lib,并将它与Babel一起用于过去的版本以避免EcmaScript不兼容。

class MyLib {
  constructor(name) {
    this.name = name;
  }

  sayHello() {
    return `Hello ${this.name}`;
  }
}

// Would this work / is this the right way?
// window.MyLib = MyLib

module.exports = MyLib;

此lib 必须在全局范围内,因为用户无需从任何地方导入它,或者甚至具有简单的HTML + CSS结构,而没有配置像webpack这样的捆绑器的开销

在全球范围内提供此lib的“正确方法”是什么?

window.MyLib = MyLib之前的module.exports是可行的,还是正确的方式?

1 个答案:

答案 0 :(得分:0)

因此,我配置了“ webpack.config.js”文件:

const path = require("path");

module.exports = {
    mode: "production",
    entry: "./index.js",
        output: {
        path: path.resolve(__dirname, "build/"),
        filename: "out_file_name.js",
        libraryTarget: 'umd',
        globalObject: 'this',
        libraryExport: 'default',
        library: 'libraryName'
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /(node_modules)/,
                use: {
                    loader: "babel-loader",
                    options: {
                        cacheDirectory: true,
                        presets: ["babel-preset-env"]
                    }
                }
            },
        ]
    }
};

在文件“ index.js”中:

function createLibraryName() {
    return {
        func1: () => {},
        func2: () => {},
        //...
    };
}

export default createLibraryName();

这样,我可以像这样访问库:

libraryName.func1();
libraryName.func2();