输出带指纹文件
我们可以使用output.filename 替换设置来定义输出文件的名称。webpack提供了一种使用称为替换的括号字符串模板化文件名的方法。该[contenthash]替代将增加基于资产的内容的唯一哈希值。当资产的内容发生变化时,[contenthash]也会发生变化。
const path = require('path');const CleanWebpackPlugin = require('clean-webpack-plugin');const HtmlWebpackPlugin = require('html-webpack-plugin');module.exports = {entry: './src/index.js',plugins: [new CleanWebpackPlugin(['dist']),new HtmlWebpackPlugin({- title: 'Output Management'+ title: 'Caching'})],output: {- filename: 'bundle.js',+ filename: '[name].[hash].js',path: path.resolve(__dirname, 'dist')}};
提取依赖
// webpack.common.jsconst path = require('path');const HtmlWebpackPlugin = require('html-webpack-plugin'); // 自动生成页面const CleanWebpackPlugin = require('clean-webpack-plugin'); // 自动清理,清理dist旧文件const webpack = require('webpack');module.exports = {// =============optimization: {runtimeChunk: 'single',splitChunks: {cacheGroups: {vendor: {test: /[\\/]node_modules[\\/]/,name: 'vendors',chunks: 'all'}}}},// =============entry: {app: './src/index.js',// print: './src/print.js',},plugins: [new CleanWebpackPlugin(['dist']),new HtmlWebpackPlugin({title: 'Output Management'}),new webpack.HotModuleReplacementPlugin(),// =============new webpack.HashedModuleIdsPlugin(),// ==============],output: {filename: '[name].[hash].js',chunkFilename: '[name].[contenthash].js',path: path.resolve(__dirname, 'dist'),publicPath: '/'},module: {rules: [{test: /\.css$/,use: ['style-loader','css-loader']},{test: /\.(png|svg|jpg|gif)$/,use: ['file-loader']},{test: /\.(woff|woff2|eot|ttf|otf)$/,use: ['file-loader']},{test: /\.(csv|tsv)$/,use: ['csv-loader']},{test: /\.xml$/,use: ['xml-loader']}],}};
输出:main的体积变小了。并且还有一个优势,当文件未发生改变时,hash值不变
第一次
Asset Size Chunks Chunk Names1ebd0482aadade65f20ec178219fe012.woff2 14.5 KiB [emitted]app.af00b1a65f2ce2ee3111.js 869 bytes 0 [emitted] appd19378a95ebe6b15d5ddea281138dcf4.svg 623 bytes [emitted]index.html 286 bytes [emitted]runtime.de5527b10e57b056999e.js 9.18 KiB 1 [emitted] runtimevendors.9d6dbdd696263a8519eb.js 69.4 KiB 2 [emitted] vendorsEntrypoint app = runtime.de5527b10e57b056999e.js app.af00b1a65f2ce2ee3111.js
第二次
Asset Size Chunks Chunk Names1ebd0482aadade65f20ec178219fe012.woff2 14.5 KiB [emitted]app.af00b1a65f2ce2ee3111.js 869 bytes 0 [emitted] appd19378a95ebe6b15d5ddea281138dcf4.svg 623 bytes [emitted]index.html 286 bytes [emitted]runtime.de5527b10e57b056999e.js 9.18 KiB 1 [emitted] runtimevendors.9d6dbdd696263a8519eb.js 69.4 KiB 2 [emitted] vendorsEntrypoint app = runtime.de5527b10e57b056999e.js app.af00b1a65f2ce2ee3111.js
当index.js发生改变时
1ebd0482aadade65f20ec178219fe012.woff2 14.5 KiB [emitted]app.89ef43d73c4a3ce088d0.js 869 bytes 0 [emitted] appd19378a95ebe6b15d5ddea281138dcf4.svg 623 bytes [emitted]index.html 286 bytes [emitted]runtime.5dea5599b4845d56ae40.js 9.18 KiB 1 [emitted] runtimevendors.9d6dbdd696263a8519eb.js 69.4 KiB 2 [emitted] vendorsEntrypoint app = runtime.5dea5599b4845d56ae40.js app.89ef43d73c4a3ce088d0.js
