gpt4 book ai didi

javascript - 哈希无效的 Webpack 缓存破坏

转载 作者:行者123 更新时间:2023-11-29 16:40:40 25 4
gpt4 key购买 nike

我正在尝试通过在每个 javascript 文件的末尾添加哈希来使用 webpack 进行缓存破坏。我的 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 缓存破坏仍然在这里工作。如果您更改代码,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 'your new config' --hot

关于javascript - 哈希无效的 Webpack 缓存破坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46348594/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com