Webpack hmr正在生产中运行

Webpack hmr正在生产中运行,webpack,webpack-hmr,Webpack,Webpack Hmr,在SPA的开发过程中,hmr发挥了巨大的作用 但是,发布时,hmr不应运行。但事实确实如此,它产生了404个错误流。为什么会这样?我看不出我做错了什么 为生产打包时,这是命令行(我从Visual Studio任务运行程序运行此命令): webpack.netcore.config.js const webpackConfig = require('./webpack.config'); const HtmlWebpackPlugin = require('html-webpack-plugin'

在SPA的开发过程中,hmr发挥了巨大的作用

但是,发布时,hmr不应运行。但事实确实如此,它产生了404个错误流。为什么会这样?我看不出我做错了什么

为生产打包时,这是命令行(我从Visual Studio任务运行程序运行此命令):

webpack.netcore.config.js

const webpackConfig = require('./webpack.config');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
var originalConfig = webpackConfig({});

module.exports = () => {
  let config = originalConfig;
  // output files without hashes
  config.output.filename = '[name].bundle.js';
  config.plugins.splice(config.plugins.indexOf(HtmlWebpackPlugin));
  config.plugins = [
    // first clean the output directory
    new CleanWebpackPlugin([config.output.path]),
    ...config.plugins
  ];

  return config;
};
webpack.config.js:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const project = require('./aurelia_project/aurelia.json');
const { AureliaPlugin, ModuleDependenciesPlugin } = require('aurelia-webpack-plugin');
const { optimize: { CommonsChunkPlugin, UglifyJsPlugin }, ProvidePlugin } = require('webpack');
const { TsConfigPathsPlugin, CheckerPlugin } = require('awesome-typescript-loader');

// config helpers:
const ensureArray = (config) => config && (Array.isArray(config) ? config : [config]) || [];
const when = (condition, config, negativeConfig) =>
  condition ? ensureArray(config) : ensureArray(negativeConfig);

// primary config:
const title = 'Aurelia Navigation Skeleton';
const outDir = path.resolve(__dirname, project.platform.output);
const srcDir = path.resolve(__dirname, 'src');
const nodeModulesDir = path.resolve(__dirname, 'node_modules');
const baseUrl = '/';

const cssRules = [
  { loader: 'css-loader' },
];

module.exports = ({production, server, extractCss, coverage} = {}) => ({
  resolve: {
    extensions: ['.ts', '.js'],
    modules: [srcDir, 'node_modules'],
  },
  entry: { 
    app: ['aurelia-bootstrapper'],
    vendor: ['bluebird','aurelia-syncfusion-bridge'],
  },
  output: {
    path: outDir,
    publicPath: baseUrl,
    filename: production ? '[name].[chunkhash].bundle.js' : '[name].[hash].bundle.js',
    sourceMapFilename: production ? '[name].[chunkhash].bundle.map' : '[name].[hash].bundle.map',
    chunkFilename: production ? '[name].[chunkhash].chunk.js' : '[name].[hash].chunk.js'
  },
  devServer: {
    contentBase: outDir,
    // serve index.html for all 404 (required for push-state)
    historyApiFallback: true
  },
  devtool: production ? 'nosources-source-map' : 'cheap-module-eval-source-map',
  module: {
    rules: [
      // CSS required in JS/TS files should use the style-loader that auto-injects it into the website
      // only when the issuer is a .js/.ts file, so the loaders are not applied inside html templates
      {
        test: /\.css$/i,
        issuer: [{ not: [{ test: /\.html$/i }] }],
        use: extractCss ? ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: cssRules
        }) : ['style-loader', ...cssRules],
      },
      {
        test: /\.css$/i,
        issuer: [{ test: /\.html$/i }],
        // CSS required in templates cannot be extracted safely
        // because Aurelia would try to require it again in runtime
        use: cssRules
      },
      { test: /\.html$/i, loader: 'html-loader' },
      { test: /\.ts$/i, loader: 'awesome-typescript-loader', exclude: nodeModulesDir },
      { test: /\.json$/i, loader: 'json-loader' },
      // use Bluebird as the global Promise implementation:
      { test: /[\/\\]node_modules[\/\\]bluebird[\/\\].+\.js$/, loader: 'expose-loader?Promise' },
      // embed small images and fonts as Data Urls and larger ones as files:
      { test: /\.(png|gif|jpg|cur)$/i, loader: 'url-loader', options: { limit: 8192 } },
      { test: /\.woff2(\?v=[0-9]\.[0-9]\.[0-9])?$/i, loader: 'url-loader', options: { limit: 10000, mimetype: 'application/font-woff2' } },
      { test: /\.woff(\?v=[0-9]\.[0-9]\.[0-9])?$/i, loader: 'url-loader', options: { limit: 10000, mimetype: 'application/font-woff' } },
      // load these fonts normally, as files:
      { test: /\.(ttf|eot|svg|otf)(\?v=[0-9]\.[0-9]\.[0-9])?$/i, loader: 'file-loader' },
      ...when(coverage, {
        test: /\.[jt]s$/i, loader: 'istanbul-instrumenter-loader',
        include: srcDir, exclude: [/\.{spec,test}\.[jt]s$/i],
        enforce: 'post', options: { esModules: true },
      })
    ]
  },
    plugins: [

    new AureliaPlugin(),
    new ProvidePlugin({
      'Promise': 'bluebird'
    }),
    new ModuleDependenciesPlugin({
      'aurelia-testing': [ './compile-spy', './view-spy' ]
    }),
    new ModuleDependenciesPlugin({
        "aurelia-orm": [
            "./component/association-select",
            "./component/view/bootstrap/association-select.html",
            "./component/view/bootstrap/paged.html",
            "./component/paged"],
        "aurelia-authentication": ["./authFilterValueConverter"]
    }),
    new TsConfigPathsPlugin(),
    new CheckerPlugin(),
    new HtmlWebpackPlugin({
      template: 'index.ejs',
      metadata: {
        // available in index.ejs //
        title, server, baseUrl
      }
    }),
    ...when(extractCss, new ExtractTextPlugin({
      filename: production ? '[contenthash].css' : '[id].css',
      allChunks: true
    })),
    ...when(production, new CommonsChunkPlugin({
      name: ['common']
    })),
    ...when(production, new CopyWebpackPlugin([
      { from: 'static/favicon.ico', to: 'favicon.ico' }
    ])),
    ...when(production, new UglifyJsPlugin({
      sourceMap: true
    }))
  ]
});

404错误如下所示:
https://trkn.app/__webpack_hmr

请详细查看抛出404的路径(未找到页面)。我想这通常是相对路径的问题。

请详细查看抛出404的路径(未找到页面)。我想这通常是相对路径的问题。

HMR在生产中运行的原因只有两个:

  • 如果您在服务器日志中看到它,这意味着该应用的开发版本仍在浏览器中打开,并且正在访问服务器

  • 如果您在客户机上看到它,这意味着在使用webpack构建时,实际没有设置生产环境

  • 这是我在webpack.config.js中设置环境的代码,然后将环境打印到控制台,确保选择了正确的环境。(请注意,此代码特定于我的开发设置(VS17+Taskrunner),因此您的里程数可能会有所不同

    const path = require("path");
    const webpack = require("webpack");
    const { AureliaPlugin, ModuleDependenciesPlugin, GlobDependenciesPlugin } = require("aurelia-webpack-plugin");
    const bundleOutputDir = "./wwwroot/dist";
    const MiniCssExtractPlugin = require("mini-css-extract-plugin");
    
    module.exports = (env, args) => {
        let isDevBuild = true;  //Assume isDevBuild;
    
        //If being run from NPM, args.mode will be populated
        if (args && args.mode === 'production') {
            isDevBuild = false;
        }
    
        //Not production mode from NPM, check on Production mode from Task Runner
        if (isDevBuild) {
            //If being run from the Webpack Task Runner in VS.
            const node_env = process.env.NODE_ENV
    
            if (node_env) {
                if (node_env === 'production') {
                    isDevBuild = false;
                }
                else {
                }
            }
        }
        //isDevBuild = true;//Uncomment to test the Prod Build
        console.log('isDevBuild=' + isDevBuild);
        const cssLoader = { loader: isDevBuild ? "css-loader" : "css-loader?minimize" };
        return [{
            target: "web",
            mode: isDevBuild ? "development" : "production",
            entry: { "app": ["es6-promise/auto", "aurelia-bootstrapper"] },
            resolve: {
                extensions: [".ts", ".js"],
                modules: ["ClientApp", "node_modules"]
            },
            output: {
                path: path.resolve(bundleOutputDir),
                publicPath: "/dist/",
                filename: "[name].js",
                chunkFilename: "[name].js"
            },
            module: {
                rules: [
                    { test: /\.(woff|woff2)(\?|$)/, loader: "url-loader?limit=1" },
                    { test: /\.(png|eot|ttf|svg|gif|cur)(\?|$)/, loader: "url-loader?limit=100000" },
                    { test: /\.ts$/i, include: [/ClientApp/, /node_modules/], use: "awesome-typescript-loader" },
                    { test: /\.html$/i, use: "html-loader" },
                    {   test: /\.css$/, include: [/node_modules/], use: [
                            {
                                loader: MiniCssExtractPlugin.loader
                            },
                            "css-loader"
                        ]
                    },
                    {
                        test: /\.css$/, exclude: [/node_modules/], use: [
                            {
                                loader: MiniCssExtractPlugin.loader
                            },
                            "css-loader"
                        ]
                    },
                    { test: /\.scss$/i, issuer: /(\.html|empty-entry\.js)$/i, use: [cssLoader, "sass-loader"] },
                    { test: /\.scss$/i, issuer: /\.ts$/i, use: ["style-loader", cssLoader, "sass-loader"] }
                ]
            },
            optimization: {
                splitChunks: {
                    cacheGroups: {
                        commons: {
                            test: /[\\/]node_modules[\\/]/,
                            name: "vendor",
                            chunks: "all"
                        }
                    }
                }
            },
            devtool: isDevBuild ? "source-map" : false,
            performance: {
                hints: false
            },
            plugins: [
                new webpack.DefinePlugin({ IS_DEV_BUILD: JSON.stringify(isDevBuild) }),
                new webpack.ProvidePlugin({ $: "jquery", jQuery: "jquery", "window.jQuery": "jquery" }),
                new webpack.ProvidePlugin({
                    'Promise': 'bluebird'
                }),
    
                new AureliaPlugin({ aureliaApp: "boot" }),
                new GlobDependenciesPlugin({ "boot": ["ClientApp/**/*.{ts,html}"] }),
                new ModuleDependenciesPlugin({}),
                //extractCSS,
                new ModuleDependenciesPlugin({
                    "aurelia-orm": [
                        "./component/association-select",
                        "./component/view/bootstrap/association-select.html",
                        "./component/view/bootstrap/paged.html",
                        "./component/paged"],
                    "aurelia-authentication": ["./authFilterValueConverter"]
                }),
    
                    new MiniCssExtractPlugin({
                        // Options similar to the same options in webpackOptions.output
                        // both options are optional
                        filename: "[name].css",
                        chunkFilename: "[id].css"
                })
    
            ]
        }];
    };
    

    还请注意,有基于isDevBuild变量设置的dev/prod功能。因此,除了设置环境外,还必须相应地设置选项。

    HMR在生产环境中运行的原因只有两个:

  • 如果您在服务器日志中看到它,这意味着该应用的开发版本仍在浏览器中打开,并且正在访问服务器

  • 如果您在客户机上看到它,这意味着在使用webpack构建时,实际没有设置生产环境

  • 这是我在webpack.config.js中设置环境的代码,然后将环境打印到控制台,确保选择了正确的环境。(请注意,此代码特定于我的开发设置(VS17+Taskrunner),因此您的里程可能会有所不同

    const path = require("path");
    const webpack = require("webpack");
    const { AureliaPlugin, ModuleDependenciesPlugin, GlobDependenciesPlugin } = require("aurelia-webpack-plugin");
    const bundleOutputDir = "./wwwroot/dist";
    const MiniCssExtractPlugin = require("mini-css-extract-plugin");
    
    module.exports = (env, args) => {
        let isDevBuild = true;  //Assume isDevBuild;
    
        //If being run from NPM, args.mode will be populated
        if (args && args.mode === 'production') {
            isDevBuild = false;
        }
    
        //Not production mode from NPM, check on Production mode from Task Runner
        if (isDevBuild) {
            //If being run from the Webpack Task Runner in VS.
            const node_env = process.env.NODE_ENV
    
            if (node_env) {
                if (node_env === 'production') {
                    isDevBuild = false;
                }
                else {
                }
            }
        }
        //isDevBuild = true;//Uncomment to test the Prod Build
        console.log('isDevBuild=' + isDevBuild);
        const cssLoader = { loader: isDevBuild ? "css-loader" : "css-loader?minimize" };
        return [{
            target: "web",
            mode: isDevBuild ? "development" : "production",
            entry: { "app": ["es6-promise/auto", "aurelia-bootstrapper"] },
            resolve: {
                extensions: [".ts", ".js"],
                modules: ["ClientApp", "node_modules"]
            },
            output: {
                path: path.resolve(bundleOutputDir),
                publicPath: "/dist/",
                filename: "[name].js",
                chunkFilename: "[name].js"
            },
            module: {
                rules: [
                    { test: /\.(woff|woff2)(\?|$)/, loader: "url-loader?limit=1" },
                    { test: /\.(png|eot|ttf|svg|gif|cur)(\?|$)/, loader: "url-loader?limit=100000" },
                    { test: /\.ts$/i, include: [/ClientApp/, /node_modules/], use: "awesome-typescript-loader" },
                    { test: /\.html$/i, use: "html-loader" },
                    {   test: /\.css$/, include: [/node_modules/], use: [
                            {
                                loader: MiniCssExtractPlugin.loader
                            },
                            "css-loader"
                        ]
                    },
                    {
                        test: /\.css$/, exclude: [/node_modules/], use: [
                            {
                                loader: MiniCssExtractPlugin.loader
                            },
                            "css-loader"
                        ]
                    },
                    { test: /\.scss$/i, issuer: /(\.html|empty-entry\.js)$/i, use: [cssLoader, "sass-loader"] },
                    { test: /\.scss$/i, issuer: /\.ts$/i, use: ["style-loader", cssLoader, "sass-loader"] }
                ]
            },
            optimization: {
                splitChunks: {
                    cacheGroups: {
                        commons: {
                            test: /[\\/]node_modules[\\/]/,
                            name: "vendor",
                            chunks: "all"
                        }
                    }
                }
            },
            devtool: isDevBuild ? "source-map" : false,
            performance: {
                hints: false
            },
            plugins: [
                new webpack.DefinePlugin({ IS_DEV_BUILD: JSON.stringify(isDevBuild) }),
                new webpack.ProvidePlugin({ $: "jquery", jQuery: "jquery", "window.jQuery": "jquery" }),
                new webpack.ProvidePlugin({
                    'Promise': 'bluebird'
                }),
    
                new AureliaPlugin({ aureliaApp: "boot" }),
                new GlobDependenciesPlugin({ "boot": ["ClientApp/**/*.{ts,html}"] }),
                new ModuleDependenciesPlugin({}),
                //extractCSS,
                new ModuleDependenciesPlugin({
                    "aurelia-orm": [
                        "./component/association-select",
                        "./component/view/bootstrap/association-select.html",
                        "./component/view/bootstrap/paged.html",
                        "./component/paged"],
                    "aurelia-authentication": ["./authFilterValueConverter"]
                }),
    
                    new MiniCssExtractPlugin({
                        // Options similar to the same options in webpackOptions.output
                        // both options are optional
                        filename: "[name].css",
                        chunkFilename: "[id].css"
                })
    
            ]
        }];
    };
    

    还请注意,有基于isDevBuild变量设置的dev/prod功能。因此,除了设置环境外,您还必须相应地设置选项。

    请参阅404错误消息。它由webpack hmr模块生成。请参阅404错误消息。它由webpack hmr模块生成。您能否更具体地介绍一下“使用webpack构建时未实际设置生产环境".我使用的是Webpack v4,我设置了
    production
    是多个位置:NODE_ENV=production&&Webpack-ENV.production,mode:production in package.json,我仍然在浏览器中遇到一个关于运行HMR的错误production@SomethingOn,您的设置是正确的。嗯,至少它们看起来是正确的。但是下面的逻辑是:如果你收到404错误,这意味着HMR请求来自客户端。如果它来自客户端,这意味着webpack包含了HMR代码。如果包含了HMR代码,这意味着环境被设置为dev,而不是production。因此,即使看起来你设置正确,最终结果仍然是dev,不是吗t prod.我更新了我的答案以包含我使用的配置文件。另一件事是,您的Web包配置文件中可能没有正确使用“isDevBuild”(参见上面的示例)对我来说,在package.json的
    scripts
    部分中,
    NODE_ENV=production webpack…
    vs
    NODE_ENV=production&&webpack…
    。显然,它不喜欢&&@SomethingOn,很高兴它得到了解决。请随意更新我的答案:)你能更具体地解释一下吗“使用webpack构建时未实际设置生产环境".我使用的是Webpack v4,我设置了
    production
    是多个位置:NODE_ENV=production&&Webpack-ENV.production,mode:production in package.json,我仍然在浏览器中遇到一个关于运行HMR的错误production@SomethingOn,您的设置是正确的。嗯,至少它们看起来是正确的。但是下面的逻辑是:如果你收到404错误,这意味着HMR请求来自客户端。如果它来自客户端,这意味着webpack包含了HMR代码。如果包含了HMR代码,这意味着环境被设置为dev,而不是production。因此,即使看起来你设置正确,最终结果仍然是dev,不是吗t prod.我更新了我的答案以包含我使用的配置文件。另一件事是,您的Web包配置文件中可能没有正确使用“isDevBuild”(参见上面的示例)对我来说,在package.json的
    scripts
    部分中,
    NODE\u ENV=production webpack…
    vs
    NODE\u ENV=production&&webpack…
    。显然,它不喜欢&&@SomethingOn,很高兴它得到了解决。请随意更新我的答案:)