【问题标题】:Webpack custom library undefined after compile编译后未定义 Webpack 自定义库
【发布时间】:2020-09-30 12:07:42
【问题描述】:

我正在构建一个 javascript 库并尝试使用 webpack 编译它。我的问题是我构建的库没有定义。我可以看到我的代码在 webpack 输出文件中,但在运行时我的库返回未定义。如果我使用未编译的库(没有 Webpack),那么一切正常。

这是我的图书馆:

import "jquery";
import "../scss/cookie-notice.scss";

void (function (root, factory) {
    if (typeof define === 'function' && define.amd) define(factory);
    else if (typeof exports === 'object') module.exports = factory();
    else root.CookieNotice = factory();
}(this, function () {

    //logic

    return CookieNotice;
}));

webpack.config.js:

const path = require("path");
module.exports = {
    mode: "development",
    devtool: "none",
    entry: "./src/js/cookie-notice.js",
    output: {
        filename: "cookie-notice.js",
        path: path.resolve(__dirname, "dist/js")
    },
    module: {
        rules: [
            {
                test: /\.(scss)$/,
                use: [
                    "style-loader",
                    "css-loader",
                    "sass-loader"
                ]
            },
        ]
    }
};

如果我尝试使用我的库,这就是我得到的错误:

有人有想法吗?

【问题讨论】:

    标签: javascript jquery webpack


    【解决方案1】:

    我是这样解决的:

    void (function (root, factory) {
        if (typeof define === 'function' && define.amd) define(factory);
        else if (typeof exports === 'object') exports['CookieNotice'] = factory();
        else root['CookieNotice'] = factory();
    }(this, function () {
       ...
    }));
    

    Webpack.config.js

    ....
    output: {
       filename: "cookie-notice.js",
       path: path.resolve(__dirname, "dist/js"),
       library: 'CookieNotice',
       libraryTarget: 'umd',
       umdNamedDefine: true,
       globalObject: 'this',
    }
    ....
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-31
      • 1970-01-01
      • 1970-01-01
      • 2017-04-28
      • 2017-07-14
      • 1970-01-01
      • 2018-07-19
      • 1970-01-01
      相关资源
      最近更新 更多