Long cache optimization solution
Long Cache Optimization Strategy
Long cache optimization is a key technique in Webpack builds to improve application loading performance. By properly configuring filename hashing, code splitting, and module identification, you can ensure that users' browsers cache as many static resources as possible, reducing redundant downloads.
Hash Strategy Selection
Webpack offers three hash generation methods:
[hash]
: Hash value for the entire project build[chunkhash]
: Hash generated based on entry files[contenthash]
: Hash generated based on file content
It is recommended to use [contenthash]
, as it only changes when the file content changes:
output: {
filename: '[name].[contenthash:8].js',
chunkFilename: '[name].[contenthash:8].chunk.js'
}
Module Identifier Stabilization
Webpack uses numeric IDs as module identifiers by default, which can cause unrelated modifications to affect the hash of all chunks. The solution is to use HashedModuleIdsPlugin
:
plugins: [
new webpack.HashedModuleIdsPlugin({
hashFunction: 'sha256',
hashDigest: 'hex',
hashDigestLength: 8
})
]
Runtime Code Separation
Extract runtime code into a separate file to prevent business code modifications from affecting runtime caching:
optimization: {
runtimeChunk: {
name: entrypoint => `runtime-${entrypoint.name}`
}
}
Third-Party Library Caching Strategy
Use separate chunks for stable third-party libraries:
splitChunks: {
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'all'
}
}
}
Dynamic Import Optimization
Use magic comments to name dynamically imported modules for cache stability:
import(/* webpackChunkName: "lodash" */ 'lodash').then(({ default: _ }) => {
// Use lodash
})
Manifest File Handling
Ensure proper generation and referencing of manifest files:
new WebpackManifestPlugin({
fileName: 'asset-manifest.json',
publicPath: '/',
generate: (seed, files) => ({
files: files.reduce((manifest, file) => {
manifest[file.name] = file.path
return manifest
}, seed)
})
})
Content Security Policy Integration
Configure appropriate Cache-Control headers and server-side caching strategies:
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
Version File Auto-Management
Create version marker files to help clients detect updates:
const { GitRevisionPlugin } = require('git-revision-webpack-plugin')
plugins: [
new GitRevisionPlugin({
versionCommand: 'describe --always --tags --dirty'
}),
new webpack.DefinePlugin({
'process.env.BUILD_VERSION': JSON.stringify(
new GitRevisionPlugin().version()
)
})
]
Preloading Critical Resources
Use preload
and prefetch
to optimize resource loading:
import(/* webpackPrefetch: true */ './path/to/Component')
Module Dependency Analysis
Use webpack-bundle-analyzer
to identify optimization opportunities:
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
plugins: [
new BundleAnalyzerPlugin({
analyzerMode: 'static',
reportFilename: 'bundle-report.html',
openAnalyzer: false
})
]
Persistent Cache Configuration
Enable filesystem caching to improve build performance:
cache: {
type: 'filesystem',
buildDependencies: {
config: [__filename]
}
}
Hash Length Optimization
Balance hash length with collision probability:
output: {
filename: '[name].[contenthash:8].js',
chunkFilename: '[name].[contenthash:8].chunk.js',
assetModuleFilename: '[name].[hash:8][ext][query]'
}
Server-Side Rendering Compatibility
Handle resource references in SSR environments:
const assets = require('./asset-manifest.json')
function renderHtml() {
return `
<!DOCTYPE html>
<html>
<head>
<link href="${assets['main.css']}" rel="stylesheet">
</head>
<body>
<script src="${assets['main.js']}"></script>
</body>
</html>
`
}
Resource Preloading Strategy
Configure resource preloading based on usage analysis:
plugins: [
new PreloadWebpackPlugin({
rel: 'preload',
include: 'initial',
fileBlacklist: [/\.map$/, /hot-update\.js$/]
})
]
Multi-Environment Configuration Handling
Differentiate cache strategies between development and production environments:
const isProduction = process.env.NODE_ENV === 'production'
output: {
filename: isProduction
? '[name].[contenthash:8].js'
: '[name].js'
}
Resource Fingerprint Verification
Ensure resource integrity:
<script
src="app.8a7b3c.js"
integrity="sha384-5N5S5Q5S5S5S5S5S5S5S5S5S5S5S5S5S5S5S5S5S5S5S5S5S5S5S5S5S5S5S5S5S5"
crossorigin="anonymous">
</script>
Build Information Injection
Embed build information into the application for easier debugging:
const { DefinePlugin } = require('webpack')
const buildDate = new Date().toISOString()
plugins: [
new DefinePlugin({
__BUILD_DATE__: JSON.stringify(buildDate),
__GIT_HASH__: JSON.stringify(require('child_process')
.execSync('git rev-parse HEAD')
.toString().trim())
})
]
Resource Loading Monitoring
Implement resource loading performance monitoring:
window.addEventListener('load', () => {
const entries = performance.getEntriesByType('resource')
const jsResources = entries.filter(
e => e.initiatorType === 'script'
)
// Report resource loading time
})
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn
上一篇:按需加载与路由懒加载
下一篇:服务端渲染优化要点