[英]Running a webpack bundled JS library with "umd" module system in Nodejs throws error: "self" is not defined
Recently I have been developing a JavaScript library and now I want to publish it on npm.最近我一直在开发一个 JavaScript 库,现在我想在 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.
所以我开始学习 webpack 并按照他们的指南Authoring a library form the docs。
In their guide they suggested using umd
module type to support all module systems so I used "umd".在他们的指南中,他们建议使用
umd
模块类型来支持所有模块系统,所以我使用了“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" !但是当我试图在Node.js中运行(通过导入)生成的包文件时,它会抛出一个异常,说“
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.然后我打开捆绑的文件,发现有一个名为
self
的变量,但我不知道它的用途是什么。
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.不管长话短说,然后我尝试
commonjs
和commonjs2
模块类型并发布了一个测试包,并在react和node环境中进行了尝试,并且效果很好。 Sadly then it didn't work in browser environment with the <script> tag.可悲的是,它在带有<script>标签的浏览器环境中不起作用。 Now my question is what module type should I use?
现在我的问题是我应该使用什么模块类型?
Here is my webpack.config.js
这是我的
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 版本:
"webpack": "^5.53.0"
"webpack-cli": "^4.8.0"
Thanks in advance.提前致谢。 I highly appreciate your time on StackOverflow <3.
我非常感谢您在 StackOverflow <3 上的时间。
After lots of time wasting I found the answer in a github issue of webpack.在浪费了很多时间之后,我在 webpack 的 github issue 中找到了答案。
I can use
library.type: "umd"<\/code> but I just have to add the following in my webpack configuration.
我可以使用
library.type: "umd"<\/code>但我只需要在我的 webpack 配置中添加以下内容。
module.exports = {
output: {
globalObject: 'this' // This line was missing
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.