Webpack 5实时重新加载

时间:2020-10-22 02:34:57

标签: javascript webpack frontend

我将webpack 4更新为webpack 5,此后一切正常,除了更新浏览器(实时重新加载),谁能说出原因?这是我的配置。

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const autoprefixer = require('autoprefixer');

module.exports = (env, argv) => {
  const { mode = 'development' } = argv;
  const isProd = mode === 'production';
  const isDev = mode === 'development';

  const getStyleLoaders = () => {
    return [isProd ? MiniCssExtractPlugin.loader : 'style-loader'];
  };
  return {
    context: path.resolve(__dirname, 'src'),
    mode: isProd ? 'production' : isDev && 'development',
    entry: './index.js',
    output: {
      path: path.resolve(__dirname, 'dist'),
      filename: isDev ? 'script/script.js' : 'script/bundle-[hash:8].js',
      publicPath: '/',
    },
    resolve: {
      extensions: ['.js'],
    },
    devServer: {
      contentBase: path.join(__dirname, 'dist'),
      publicPath: '/',
      open: true,
      watchContentBase: true,
      port: 8080,
    },
    devtool: isProd ? false : 'source-map',
  };
};

5 个答案:

答案 0 :(得分:8)

您需要在Webpack配置中设置{target: 'web'},并确保像这样运行您的开发服务器:webpack serve --mode development --env development

答案 1 :(得分:0)

我不确定这是否与您的问题有关,但是您使用的是哪个版本的webpack-cli?由于 webpack-cli v4.0.0 ,一些人正在报告 webpack-dev-server 的问题:

Error: Cannot find module 'webpack-cli/bin/config-yargs' #2759

如果遇到此问题,可以尝试将 webpack-cli 降级至版本:3.3.0(完全),将 webpack-dev-server 降级至版本: ^ 3.11.0。

答案 2 :(得分:0)

仅当 webpack 捆绑包目标为“web”时,实时重新加载才有效, 因此,将此行添加到 webpack.config 将使其工作:

target: 'web'

不过,在编写本文时,webpack-dev-server@3 中存在一个错误,当目标是包含“web”的数组时,会阻止实时重新加载: https://github.com/webpack/webpack-dev-server/pull/3271

所以你不能这样做:

target: ['web', 'es5']

也许可以使用这种解决方法...

target: isProduction ? ['web', 'es5'] : 'web'

答案 3 :(得分:0)

我遇到了同样的问题 webpack v5.39.0, webpack-cli v4.7.2 webpack-dev-server v3.11.2 我的方式:

<块引用>

npm install -D webpack-dev-server@4.0.0-beta.0

module.exports ={target: "web"} 在配置中

和 package.json 中的 "start": "webpack serve"

答案 4 :(得分:0)

我有同样的错误,这是修复它的原因:

第一次

在 Webpack 配置中设置 {target: 'web'}

在 devServer 配置集下: publicPath: "/assets/",

我的配置将:

    module.exports = {
    target: “web”,
    entry: {
    main: path.resolve(__dirname, “./src/index.js”)
    },
    output: {
    path: __dirname + “/dist/assets”,
    filename: “bundle.js”,
    publicPath: “assets”
    },
    mode: “development”,
    devServer: {
    open: true,
    contentBase: “./dist”,
    publicPath: “/assets/”,
    port: 3000,
    hot: false,
    watchContentBase: true
    }}