09. 缓存

108 阅读1分钟

相关代码

通过缓存,可以降低网络流量,使网站加载速度更快。但是,如果在部署新版本时不更改资源的文件名,浏览器可能会认为它没有被更新,就会使用资源的缓存版本。

Webpack 中可以使用一些配置,以确保编译生成的文件能够被客户端缓存,且当文件内容变化后,仍然能够请求到新的文件。

一、输出文件的文件名

Webpack 提供了 substitution(可替换模板字符串)。其中:

  • [name] 可以读取到 entry 中每个 chunk 的名字;
  • [contenthash] 将根据资源内容创建出唯一 hash,当资源内容发生变化时,[contenthash] 也会发生变化,打包出来的文件名会随之变化。
module.exports = {
    entry: {
        index: './src/index.js'
    },
    output: {
        filename: '[name].[contenthash].js',
    },
}

二、缓存第三方库

因为第三方库代码不像本地源代码一样频繁修改,所以可以将第三方库文件提取到单独的文件中,利用客户端的长效缓存机制,命中缓存来消除请求,减少向服务器获取资源。

optimization.splitChunks 添加 cacheGroups 参数:

module.exports = {
    optimization: {
        splitChunks: {
            cacheGroups: {
                vendor: { 
                    test: /[\\/]node_modules[\\/]/, 
                    name: 'vendors', 
                    chunks: 'all'
                }
            }
        }
    }
}

image.png

三、将 js 文件放到一个文件夹中

module.exports = {
    output: {
        filename: 'scripts/[name].[contenthash].js',
    },
}