繁体   English   中英

Webpack: 库变量未定义

[英]Webpack: library var is not defined

尝试使用我的 Webpack 捆绑库时,主库变量出现undefined错误。

我尝试了 StackOverflow 的许多不同解决方案,例如在我的 webpack.config 中使用globalObject: 'this' ,但 StackOverflow 的解决方案似乎都不起作用。

代码非常简单,我看不出它会抛出错误的任何原因,但出于某种原因确实如此。

这是我的 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()
   ],
 };

源代码/index.js:

export var test  = 0;

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>

使用 webpack-dev-server 运行时,我在第 1.html 页收到以下错误:

Uncaught ReferenceError: sdnd is not defined at 1.html:34:23

在捆绑的main.js文件中有一行sdnd = __webpack_exports__; ,所以我不明白为什么它不起作用

解决了:

我收到错误的原因是因为HtmlWebpackPlugin - 它向加载的脚本添加了一个defer属性,这导致在加载包之前执行内联脚本。 我通过添加scriptLoading: "blocking"inject: "head"属性到HtmlWebpackPlugin调用来解决这个问题

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM