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.
In their guide they suggested using umd module type to support all module systems so I used "umd". But when I tried to run (via importing) the generated bundle file in Node.js, it throws an exception saying "self is not defined"! Then I opened the bundled file and 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 with the <script> tag. 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 your time on StackOverflow <3.
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With