【发布时间】:2020-09-25 03:14:42
【问题描述】:
我正在使用 Webpack 5、html-webpack-plugin 和 html-loader 开发一个网站。
这是我的index.html:
<!DOCTYPE html>
<html>
<head>
<title>test page</title>
</head>
<body>
<p>hello there</p>
<script type="application/javascript" src="../script/index.ts">
</script>
</body>
</html>
这是我的index.ts:
console.log('hi');
document.body.append('this isnt hmr but its not bad for a static site generator');
document.body.append('ree');
这是我webpack.config.js的相关部分:
module.exports = async (env) => {
return {
// ...
module: {
rules: [
// ...
{
test: /\.html$/i,
use: ['html-loader'],
},
],
},
plugins: [
// ...
new HtmlPlugin({
template: '../path/to/index.html',
filename: 'index.html',
})
],
// ...
};
};
当我尝试编译它时,我收到以下错误:
ERROR in Error: webpack-internal:///608:2 document.body.append('this isnt hmr but its not bad for a static site generator'); ^ ReferenceError: document is not defined - 608:2 eval webpack-internal:///608:2:1 - index.html:21 Object.608 /home/laptou/website/client/source/page/index.html:21:1 - index.html:71 __webpack_require__ /home/laptou/website/client/source/page/index.html:71:41 - 673:3 eval webpack-internal:///673:3:34 - index.html:48 Object.673 /home/laptou/website/client/source/page/index.html:48:1 - index.html:71 __webpack_require__ /home/laptou/website/client/source/page/index.html:71:41 - index.html:81 /home/laptou/website/client/source/page/index.html:81:18 - index.html:82 /home/laptou/website/client/source/page/index.html:82:12 - index.js:320 HtmlWebpackPlugin.evaluateCompilationResult [client]/[html-webpack-plugin]/index.js:320:28
为什么我的index.ts 中的代码会被评估,而不是被捆绑,我该如何阻止这种情况发生?
编辑:
-
我查看了this question,但我觉得我的问题不同,因为我遇到了不同的错误。我的链中已经有一个 Babel 加载器,所以所有的代码都应该是完全易于消化的纯 JS。
-
我查看了this question and its answer also,但我不想使用 Parcel,因为我无法让它的 glob 导入正确且一致地工作,而且它没有 Webpack 所拥有的所有功能和社区支持。
【问题讨论】:
-
尝试使用 window.onload 导入
-
@SaianshSingh 这有什么帮助?此错误发生在编译时;它只会说
window没有定义。
标签: javascript webpack html-webpack-plugin