【问题标题】:Why doesn't importing scripts from <script> tags work under html-loader?为什么从 <script> 标签导入脚本在 html-loader 下不起作用?
【发布时间】:2020-09-25 03:14:42
【问题描述】:

我正在使用 Webpack 5、html-webpack-pluginhtml-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


【解决方案1】:

我在你的 webpack.config.js 和你的 index.html 模板中发现了几个问题。

您的模板直接尝试包含 index.ts,即 typescript。 但是插件会注入捆绑的脚本,所以你不应该指定脚本标签 你自己。 您的项目中有打字稿,但没有使用打字稿加载器指定规则。 你提到你正在使用'html-webpack-plugin', 但是您指定的插件拼写不同。

关于错误的最后提示: 每当我遇到“文档未定义”时, 一直是因为 webpack loader 规则配置不一致, 这会导致 webpack 在错误类型的输入上执行加载器, 这导致奇怪的“世界没有定义!”各种错误。

否则在客户端打字稿/javascript 时会出现“未定义文档” 错误地包含在 SSR(服务器端渲染)和/或 nodeJS/服务器端上下文中。

【讨论】:

    猜你喜欢
    • 2018-05-05
    • 1970-01-01
    • 2011-03-15
    • 2021-11-17
    • 2014-05-11
    • 1970-01-01
    • 2016-08-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多