Skip to content
Advertisement

Webpack custom library undefined after compile

I am building a javascript library and try to compile it with webpack. My problem is the library I build are not defined. I can see my code are in the webpack output file but at run time my library returned undefined. If I use my library uncompiled (without Webpack), then everything is working fine.

This is my library:

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"
                ]
            },
        ]
    }
};

And this is the error I get if I try to use my library: enter image description here

enter image description here

Does someone has an idea?

Advertisement

Answer

I fixed it like this:

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',
}
....
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement