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.
module.exports = {
output: {
globalObject: 'this' // This line was missing
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.