通过缓存体改页面的运行速度。
浏览器在第一次进入一个页面时是会缓存这个页面的数据的,当页面内容修改(发起过请求等),在请求时会先将新请求下来的文件和之前请求的文件进行对比,如果文件名不一样,就将不一样的文件重新下载,其余文件用缓存中的。所以如果在请求时文件名并没有改变(内容以改变),这时是不会重新获取最新数据的,这回导致网页不会显示最新的内容。
通过substitution可替换的模板字符串,让文件在有过修改后就会重新打包,这样就不会由上面的情况了。
const path = require("path")
const HtmlWebpackPlugin = require("html-webpack-plugin")
module.export = {
// 配置多入口
entry:{
index:"./src/index.js",
another:"./src/another-module.js"
},
output:{
// [name]这种类型,是叫做substitution可替换的模板字符串
// 这种写法让文件名可以随着文件内容的变化而变化,
filename:"[name].[contenthash].js",
path:path.resolve(__dirname,"./dist"),
clean:true,
assetModuleFilename:"images/[contenthash][ext]"
},
// mode:"development",
// devtool:"inline-source-map",
// plugins: [
// new HtmlWebpackPlugin({
// template:"./index.html",
// filename:"app.html",
// inject:"body"
// })
// ],
// 定义哪些资源文件需要打包
module:{
rules:[
// ...
]
},
// 优化插件
optimization:{
// 压缩代码
minimizer:{
new CssMinimizerPlugin()
},
// 分离代码
// 配置后,将会自动把公共的代码抽离到单独的文件中
// splitChunks:{
// chunks:"all"
// }
}
}
缓存第三方库
const path = require("path")
const HtmlWebpackPlugin = require("html-webpack-plugin")
module.export = {
// 配置多入口
entry:{
index:"./src/index.js",
another:"./src/another-module.js"
},
output:{
// [name]这种类型,是叫做substitution可替换的模板字符串
// 这种写法让文件名可以随着文件内容的变化而变化,
filename:"scripts/[name].[contenthash].js",
path:path.resolve(__dirname,"./dist"),
clean:true,
assetModuleFilename:"images/[contenthash][ext]"
},
// mode:"development",
// devtool:"inline-source-map",
// plugins: [
// new HtmlWebpackPlugin({
// template:"./index.html",
// filename:"app.html",
// inject:"body"
// })
// ],
// 定义哪些资源文件需要打包
module:{
rules:[
// ...
]
},
// 优化插件
optimization:{
// 压缩代码
minimizer:{
new CssMinimizerPlugin()
},
// 分离代码
// 配置后,将会自动把公共的代码抽离到单独的文件中
splitChunks:{
// 缓存组
// 一般用于定义需要缓存的第三方库
cacheFGroups:{
// 第三方库一般都是在node_modules中的
vendor:{
// 这样配置,是为了确保能获取到node_modules中的文件
test:/[\\/]node_modules[\\/]/,
// 起个名字
name:"vendors",
// all 对所有chunks(模块)做处理
chunks:"all"
}
}
}
}
}
打包后,所有的第三方包都会打包到一个vendors.bundle.js的打包文件中
将所有的js文件放到一个单独的文件中
只需要在导出文件前定义js文件存放的位置,如下:
配置后,所有的js打包文件都会放到scripts文件下