[英]Webpack: library var is not defined
I'm getting an undefined
error for the main library variable when trying to use my Webpack bundled library.尝试使用我的 Webpack 捆绑库时,主库变量出现undefined
错误。
I tried many different solutions from StackOverflow, such as using globalObject: 'this'
in my webpack.config, but none of the solutions from StackOverflow seem to be working.我尝试了 StackOverflow 的许多不同解决方案,例如在我的 webpack.config 中使用globalObject: 'this'
,但 StackOverflow 的解决方案似乎都不起作用。
The code is very simple and I don't see any reason why it would be throwing an error, but for some reason it is.代码非常简单,我看不出它会抛出错误的任何原因,但出于某种原因确实如此。
This is my webpack.config:这是我的 webpack.config:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const HtmlWebpackHarddiskPlugin = require('html-webpack-harddisk-plugin');
function gen_html_example(filename, title){
return new HtmlWebpackPlugin({
title: title,
filename: "examples/" + filename,
template: "./src/examples/" + filename,
alwaysWriteToDisk: true
})
}
module.exports = {
entry: './src/index.js',
mode: 'development',
devtool: 'inline-source-map',
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist'),
libraryTarget: "var",
library: "sdnd",
clean: true,
},
devServer: {
static: './dist/examples',
},
plugins: [
new HtmlWebpackPlugin({
title: 'Index',
filename: "examples/index.html",
template: "./src/examples/index.html",
alwaysWriteToDisk: true,
}),
gen_html_example("1.html", "Example #1"),
new HtmlWebpackHarddiskPlugin()
],
};
src/index.js:源代码/index.js:
export var test = 0;
1.html: 1.html:
<!DOCTYPE html>
<html>
<head>
<style>
.droppable{
background-color: lightgray;
width: 100%;
height: 50px;
cursor: move;
}
#dropzone{
width: 400px;
height: 400px;
border: 1px solid black;
padding: 5px;
box-sizing: border-box;
}
</style>
<script defer src="../main.js"></script>
</head>
<body>
<div id="dropzone">
</div>
<script>
const a = sdnd.test;
</script>
</body>
</html>
I'm getting the following error on page 1.html when running with webpack-dev-server:使用 webpack-dev-server 运行时,我在第 1.html 页收到以下错误:
Uncaught ReferenceError: sdnd is not defined at 1.html:34:23
In the bundled main.js
file there is a line sdnd = __webpack_exports__;
在捆绑的main.js
文件中有一行sdnd = __webpack_exports__;
, so I don't understand why it wouldn't be working ,所以我不明白为什么它不起作用
The reason I was getting the error is because of HtmlWebpackPlugin
- it was adding a defer
attribute to the loaded script, which caused the inline script to be executed before the bundle had been loaded.我收到错误的原因是因为HtmlWebpackPlugin
- 它向加载的脚本添加了一个defer
属性,这导致在加载包之前执行内联脚本。 I resolved this by adding scriptLoading: "blocking"
and inject: "head"
properties to HtmlWebpackPlugin
calls我通过添加scriptLoading: "blocking"
和inject: "head"
属性到HtmlWebpackPlugin
调用来解决这个问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.