webpack-dev-server v4 -window 未定义

webpack-dev-server v4 -window is not defined

您好,我升级到 Webpack 5,版本如下:

  // package.json
  "webpack": "^5.11.1",
  "webpack-cli": "^4.3.1",
  "webpack-dev-server": "^4.0.0-beta.0",

我正在使用以下配置 webpack-dev-server -d source-map --mode=development 启动开发服务器:

// webpack.config.json
{
      entry,
      output: {
         filename: '[name].[fullhash].js',
         path: path.resolve(__dirname, 'build'),
         publicPath: '/',
      },
      resolve: {
         extensions: [
            '.js',
            '.jsx',
            '.ts',
            '.tsx',
         ],
         alias,
      },
      context: path.resolve(__dirname, 'src'),
      devServer: {
         static: path.resolve(__dirname, 'build'),
         public: 'localhost:3000',
         open: true,
         historyApiFallback: true,
         port: 3000,
         proxy: {
            '^/': 'http://localhost:3000'
         },
      },
      plugins: [
         new WebpackDotenv(),
         new HtmlWebpackPlugin({
            template: 'index.html',
            collapseWhitespace: true,
            removeComments: true,
         }),
         new MiniCssExtractPlugin({
            filename: 'styles.css',
         }),
         new SVGSpritemapPlugin(
            '/assets/icons',
            {
               output: {
                  filename: 'spritemap.svg',
               }
            }
         ),
      ],
      stats: {
         assets: true,
         assetsSort: 'size',
         all: false,
         errors: true,
         colors: true,
         performance: true,
         timings: true,
      },
      optimization: {
         minimizer: [
            new OptimizeCSSAssetsPlugin({}),
            new TerserPlugin({
               // Use multi-process parallel running to improve the build speed
               // Default number of concurrent runs: os.cpus().length - 1
               parallel: true,
               // Enable file caching
               extractComments: false,
            }),
            new UglifyJsPlugin({
               uglifyOptions: {
                  output: {
                     comments: false,
                  }
               }
            }),
         ],
      },
      module: {
         rules: [
            {
               test: /\.ts(x?)$/,
               exclude: /node_modules/,
               use: {
                  loader: 'swc-loader',
                  options: {
                     sync: true
                  }
               },
            },
            {
               // TODO: somehow the sourcemap is not being generated properly
               test: /\.s(a|c)ss$/,
               use: [
                  {
                     loader: 'style-loader',
                  },
                  {
                     loader: 'css-loader',
                     options: {
                        sourceMap: true,
                     }
                  },
                  { loader: 'resolve-url-loader' },
                  {
                     loader: 'postcss-loader',
                     options: {
                        postcssOptions: {
                           plugins: [
                              require('autoprefixer'),
                           ],
                        },
                     },
                  },
                  {
                     loader: 'sass-loader',
                  }
               ],
            },
            {
               test: /\.css$/,
               use: [
                  MiniCssExtractPlugin.loader,
                  'css-loader',
               ],
            },
            {
               test: /\.(ttf|eot|woff|woff2)$/,
               use: {
                  loader: 'file-loader',
                  options: {
                     name: '[name].[ext]',
                     outputPath: 'fonts/',
                     publicPath: '/fonts',
                     esModule: false,
                  },
               },
            },
            {
               test: /\.(gif|png|jpe?g|svg)$/i,
               use: [
                  {
                     loader: 'file-loader',
                     options: {
                        name: '[name].[ext]',
                        outputPath: 'images/',
                        publicPath: '/images',
                     }
                  }
               ],
            },
         ],
      },
      devtool: 'source-map',
   }

一切正常,除了我收到以下错误:

// browser console
Uncaught ReferenceError: window is not defined
    at Object.../node_modules/webpack-dev-server/client/default/index.js

可以找到相关文件 here。一切似乎都工作正常,即使有错误。但是开发的时候一直报这个错感觉不好

关于如何消除此错误并将 window 对象提供给 webpack 开发服务器的任何建议?

如果您可以修补 index.ts 并将所有 window 调用替换为:

(() => {
    if (typeof self !== 'undefined') {
        return self;
    } else if (typeof window !== 'undefined') {
        return window;
    } else if (typeof global !== 'undefined') {
        return global;
    } else {
        return Function('return this')();
    }
})()

那么这应该可以工作。

这里的问题是,在我的 entry 变量中,我得到了两件事。一个是应用程序本身,另一个是它的service-worker。后面结合开发模式才是报错的原因。所以我只是在注册我的 service-worker.

之前检查 process.env.NODE_ENV !== 'development'

不是真正的解决方案,但足以满足我的用例。