Home > other >  Running a webpack bundled JS library with "umd" module system in Nodejs throws error: &quo
Running a webpack bundled JS library with "umd" module system in Nodejs throws error: &quo

Time:09-26

Recently I have been developing a JavaScript library and now I want to publish it on npm. Then I learned that I've to use a package bundler. So I started learning webpack and followed their guide Authoring a library form the docs.

The problem is in their guide they told to use umd to support all module system. But when I use umd module and generate the bundle and try to use it, it throws an exception saying self is not defined. Then I opened the bundled file found that there is a variable named self but I don't know what is its purpose.

Whatever long story short, then I tried commonjs and commonjs2 module type and published a test package and tried it in both react and node environment and it worked perfectly. Sadly then it didn't work in browser environment. Now my question is what module type should I use?

Here is my webpack.config.js

const path = require("path");

module.exports = {
  mode: "production",
  entry: "./src/index.js",
  output: {
    path: path.resolve(__dirname, "dist"),
    filename: "index.js",
    library: {
      type: "commonjs", // umd, commonjs2, ....
    },
  },
};

Here is my project structure

|- /dist
|- /src
|- package.json
|- webpack.config.json

Webpack versions:

"webpack": "^5.53.0"
"webpack-cli": "^4.8.0"

Thanks in advance. I highly appreciate you time on StackOverflow <3.

CodePudding user response:

After lots of time wasting I found the answer in a github issue of webpack.

I can use library.type: "umd" but I just have to add the following in my webpack configuration.

module.exports = {
  output: {
    globalObject: 'this' // This line was missing
  }
}
  • Related