使用哈希值进行Webpack缓存破坏无法正常工作

3

我正在尝试使用webpack进行缓存破坏,通过在每个javascript文件的末尾添加哈希值。我的webpack配置文件如下:

const AssetsPlugin = require('assets-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
//const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    entry: "./js/main.js",
    output: {
        path: __dirname + '/static/',
        publicPath: '',
        filename: "bundle-[hash].js",
    },
    resolveLoader: {
    moduleExtensions: ['-loader']
    },
    module: {
        loaders: [
            {
                test: /\.jsx?$/,
                exclude: /(node_modules|bower_components)/,
                loader: 'babel',
                query: {
                    presets: ['react', 'es2015', 'stage-0']
                }
            },
            {
                test: /\.css$/,
                loader: 'style-loader',
            },
            {
                test: /\.css$/,
                loader: 'css-loader',
                query: {
                    modules: true,
                    localIdentName: '[name]__[local]___[hash:base64:5]'
                }
            }
        ]
    },
    plugins: [
        new CleanWebpackPlugin(['static/bundle*.js'], {watch: true}),
        new AssetsPlugin({
                filename: 'static/webpack.assets.json',
                prettyPrint: true
        }),
    ]
};

以下是服务于webpack创建的javascript文件的index.html文件:
<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript" >
            $.getJSON('webpack.assets.json', function(data){
                <!--
                var bundleScript = "<script src=" + data['main']['js'] + "></script>";
                var div = document.getElementById('app');
                div.innerHTML = bundleScript;
                $(bundleScript).appendTo('#app');
                //!-->
            });
        </script>
    </head>

    <body>
        <div id="app"></div>
    </body>
</html>

当我修改代码时,我需要强制刷新浏览器才能看到更改的内容,而不是像我期望的那样进行普通刷新,这可能与缓存破坏无关。如有帮助,感谢!

我认为在webpack服务器运行脚本中添加--watch将会有所帮助。 - Gaurav Paliwal
3个回答

5

Webpack缓存破坏在此仍然有效。如果更改代码,Webpack将使用不同的哈希重新创建文件(https://webpack.js.org/guides/caching)

你想要的是热重载。你可以在https://webpack.js.org/concepts/hot-module-replacement/中了解更多信息。

要使用热重载,您应该创建新的配置:

const AssetsPlugin = require('assets-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');

module.exports = {
entry: "./js/main.js",
output: {
    path: __dirname + '/static/',
    publicPath: '',
    filename: "bundle.js", // remove hash
},
resolveLoader: {
moduleExtensions: ['-loader']
},
module: {
    loaders: [
        {
            test: /\.jsx?$/,
            exclude: /(node_modules|bower_components)/,
            loader: 'babel',
            query: {
                presets: ['react', 'es2015', 'stage-0']
            }
        },
        {
            test: /\.css$/,
            loader: 'style-loader',
        },
        {
            test: /\.css$/,
            loader: 'css-loader',
            query: {
                modules: true,
                localIdentName: '[name]__[local]___[hash:base64:5]'
            }
        }
    ]
},
plugins: [
    // new CleanWebpackPlugin(['static/bundle*.js'], {watch: true}), comment it
    // new AssetsPlugin({
    //        filename: 'static/webpack.assets.json',
    //        prettyPrint: true
    // }), and this 
],
devServer: {
  contentBase: path.join(__dirname, "static"),
  compress: true,
  port: 9000
}
};

并运行以下命令:webpack-dev-server -c '你的新配置' --hot


嗨,imcvampire,感谢提供的链接。您能否附上一些关于“热重载”的代码呢?谢谢。 - Alex

2

index.html 只会被浏览器加载一次。在这个 html 文件中编写的用于加载资源的代码也只会在浏览器中运行一次。一旦您更改了代码,webpack 可以创建一个新的捆绑包,并使用新的哈希名称,但是您的浏览器不知道这一点,并且不会自动下载新的资产文件。这就是为什么您的更改不会反映在浏览器中的原因。缓存清除通常用于生产构建。对于开发环境,使用热模块重新加载。以下是 hmr 的示例。

webpack.config.dev.js

/**
 * Created by ishan.trivid on 28-06-2016.
 */
import webpack from "webpack";
import path from "path";

export default {
debug: true,
devtool: "cheap-module-eval-source-map",
noInfo: true,
entry: [
    "eventsource-polyfill", // necessary for hot reloading with IE
    "webpack-hot-middleware/client?reload=true", //note that it reloads the page if hot module reloading fails.
    "./src/index"
],
target: "web",
output: {
    path: __dirname + "/dist", // Note: Physical files are only output by the production build task `npm run build`.
    publicPath: "/",
    filename: "bundle.js"
},
devServer: {
    contentBase: "./src"
},
plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin()
],
module: {
    loaders: [
        {test: /\.js$/, include: path.join(__dirname, "src"), loaders: ["babel"]},
        {test: /(\.css)$/, loaders: ["style", "css"]},
        {test: /\.(png)$/, loader: "url-loader?limit=1000000"},
        {test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: "file"},
        {test: /\.(woff|woff2)$/, loader: "url?prefix=font/&limit=5000"},
        {test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=application/octet-stream"},
        {test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=image/svg+xml"}
    ]
}
};

srcServer.js

import express from "express";
import webpack from "webpack";
import path from "path";
import config from "./webpack.config.dev";
import open from "open";

const port = 3000;
const app = express();
const compiler = webpack(config);

app.use(require("webpack-dev-middleware")(compiler, {
    noInfo: true,
    publicPath: config.output.publicPath
}));

app.use(require("webpack-hot-middleware")(compiler));

app.get("*", function(req, res) {
    res.sendFile(path.join( __dirname, "../src/index.html"));
});

app.listen(port, function(err) {
    if (err) {
        console.log(err);
    } else {
        open(`http://localhost:${port}`);
    }
});

现在在package.json文件的脚本部分添加以下命令:

"start": "babel-node srcServer.js"

现在在终端运行"npm run start"命令。


很好的回答,但是在生产环境中如何清除缓存index.html呢? - scipper
嘿 @scipper,你有关于“在生产环境中缓存破坏index.html”的任何东西吗?这对我很有帮助。 - Mohd Maaz

1

这是我的配置文件示例

安装Babel HMRE插件

npm install --save-dev babel-preset-react-hmre


module.exports = {
  // entry and output options

  module: {
    loaders: [{
      test: /\.js$/,
      exclude: /node_modules/,
      loader: "babel",
      include: __dirname,
      query: {
        presets: [ 'es2015', 'react', 'react-hmre' ]
      }
    }]
  }
}

并在package.json中编辑您的启动脚本以启用热更新选项:

"start": "webpack-dev-server --progress --inline --hot",

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接