通过缓存体改页面的运行速度。
image.png
浏览器在第一次进入一个页面时是会缓存这个页面的数据的,当页面内容修改(发起过请求等),在请求时会先将新请求下来的文件和之前请求的文件进行对比,如果文件名不一样,就将不一样的文件重新下载,其余文件用缓存中的。所以如果在请求时文件名并没有改变(内容以改变),这时是不会重新获取最新数据的,这回导致网页不会显示最新的内容。
通过substitution可替换的模板字符串,让文件在有过修改后就会重新打包,这样就不会由上面的情况了。

  1. const path = require("path")
  2. const HtmlWebpackPlugin = require("html-webpack-plugin")
  3. module.export = {
  4. // 配置多入口
  5. entry:{
  6. index:"./src/index.js",
  7. another:"./src/another-module.js"
  8. },
  9. output:{
  10. // [name]这种类型,是叫做substitution可替换的模板字符串
  11. // 这种写法让文件名可以随着文件内容的变化而变化,
  12. filename:"[name].[contenthash].js",
  13. path:path.resolve(__dirname,"./dist"),
  14. clean:true,
  15. assetModuleFilename:"images/[contenthash][ext]"
  16. },
  17. // mode:"development",
  18. // devtool:"inline-source-map",
  19. // plugins: [
  20. // new HtmlWebpackPlugin({
  21. // template:"./index.html",
  22. // filename:"app.html",
  23. // inject:"body"
  24. // })
  25. // ],
  26. // 定义哪些资源文件需要打包
  27. module:{
  28. rules:[
  29. // ...
  30. ]
  31. },
  32. // 优化插件
  33. optimization:{
  34. // 压缩代码
  35. minimizer:{
  36. new CssMinimizerPlugin()
  37. },
  38. // 分离代码
  39. // 配置后,将会自动把公共的代码抽离到单独的文件中
  40. // splitChunks:{
  41. // chunks:"all"
  42. // }
  43. }
  44. }

缓存第三方库

image.png

  1. const path = require("path")
  2. const HtmlWebpackPlugin = require("html-webpack-plugin")
  3. module.export = {
  4. // 配置多入口
  5. entry:{
  6. index:"./src/index.js",
  7. another:"./src/another-module.js"
  8. },
  9. output:{
  10. // [name]这种类型,是叫做substitution可替换的模板字符串
  11. // 这种写法让文件名可以随着文件内容的变化而变化,
  12. filename:"scripts/[name].[contenthash].js",
  13. path:path.resolve(__dirname,"./dist"),
  14. clean:true,
  15. assetModuleFilename:"images/[contenthash][ext]"
  16. },
  17. // mode:"development",
  18. // devtool:"inline-source-map",
  19. // plugins: [
  20. // new HtmlWebpackPlugin({
  21. // template:"./index.html",
  22. // filename:"app.html",
  23. // inject:"body"
  24. // })
  25. // ],
  26. // 定义哪些资源文件需要打包
  27. module:{
  28. rules:[
  29. // ...
  30. ]
  31. },
  32. // 优化插件
  33. optimization:{
  34. // 压缩代码
  35. minimizer:{
  36. new CssMinimizerPlugin()
  37. },
  38. // 分离代码
  39. // 配置后,将会自动把公共的代码抽离到单独的文件中
  40. splitChunks:{
  41. // 缓存组
  42. // 一般用于定义需要缓存的第三方库
  43. cacheFGroups:{
  44. // 第三方库一般都是在node_modules中的
  45. vendor:{
  46. // 这样配置,是为了确保能获取到node_modules中的文件
  47. test:/[\\/]node_modules[\\/]/,
  48. // 起个名字
  49. name:"vendors",
  50. // all 对所有chunks(模块)做处理
  51. chunks:"all"
  52. }
  53. }
  54. }
  55. }
  56. }

打包后,所有的第三方包都会打包到一个vendors.bundle.js的打包文件中

将所有的js文件放到一个单独的文件中

只需要在导出文件前定义js文件存放的位置,如下:
image.png
配置后,所有的js打包文件都会放到scripts文件下