资讯专栏INFORMATION COLUMN

Webpack包教不包会

harriszh / 3447人阅读

摘要:是什么本质上,是一个现代应用程序的静态模块打包器。当处理应用程序时,它会递归地构建一个依赖关系图,其中包含应用程序需要的每个模块,然后将所有这些模块打包成一个或多个。通过将选项设置为,启用代码压缩和。

Webpack是什么?

</>复制代码

  1. 本质上,webpack 是一个现代 JavaScript 应用程序的静态模块打包器(module bundler)。当 webpack处理应用程序时,它会递归地构建一个依赖关系图(dependency graph),其中包含应用程序需要的每个模块,然后将所有这些模块打包成一个或多个 bundle。 ——Webpack文档

简单来说 Webpack就是一个前端项目的打包工具,精简一下就是:Webpack就是个工具

WebPack打包方式有什么特点?

WebPack以JavaScript为入口(entry);通过不同的loader,处理不同格式的资源(file资源file-loader/url-loader,css资源style-loader/css-loader,JavaScript资源babel-loader,等);通过html-webpack-plugin动态生成html文件并插入CSS、JavaScript资源;通过output配置已经处理过的文件,包括文件的名称(filename)、生成文件放置位置(path)、线上资源服务路径(publicPath),非入口文件名称(chunkFilename)等。

WebPack的常用配置是什么?

entry WebPack的入口,打包入口文件的配置

output Webpack的出口,输出打包后的文件配置

mode 配置的模式 development (开发模式) / production(生产模式) / none

module 模块的处理方式 在这里使用各种loader处理不同的资源

plugins WebPack常用的一些插件 包括动态生成Html,将CSS生成文件等等

devtool 调试方式 source-map等,

resolve 设置模块如何被解析 alias 地址简写 extensions 后缀自动查找等

context: 基础目录,绝对路径,用于从配置中解析入口起点(entry point)和 loader

WebPack的entry配置有几种常用方式?

</>复制代码

  1. 1 "./index.js"
  2. 2 {
  3. index: "./index.js"
  4. }
  5. 3 ["webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000&reload=true", "./index.js"]
  6. 4 {
  7. index: ["webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000&reload=true",
  8. , "./index.js"]
  9. }

第二种常在打包生成上线文件时使用,第四种模式在多页面需要进行HMR时,
第三种模式在进行SPA页面开发时,或者在优化多页面HMR过程,HtmlWebpackPlugin生成Html文件比较耗时,这时可以专注于当前开发的页面,即只打包当前开发的页面,减少需要重新生成的文件。

WebPack的output配置有几种参数?

</>复制代码

  1. output: {
  2. filename: "static/[name].js",
  3. path: path.resolve(__dirname, "dist"),
  4. publicPath: "/"
  5. chunkFileName: ""
  6. }

filename: 文件名称 可以类似static/[name].js这样书写,可以增加一个static文件夹
path 输出的路径
publicPath 服务器防止资源文件的路径
chunkFileName 非入口文件
WebPack的mode配置有几种设置?

</>复制代码

  1. production development none

如果不设置,按照production方式

WebPack的常用module怎么配置?

</>复制代码

  1. module: {
  2. rules: [
  3. {
  4. test: /.css$/,
  5. use: [
  6. {
  7. loader: MiniCssExtractPlugin.loader,
  8. options: {
  9. // you can specify a publicPath here
  10. // by default it uses publicPath in webpackOptions.output
  11. hmr: process.env.NODE_ENV === "development",
  12. },
  13. },
  14. "css-loader"
  15. ]
  16. },
  17. {
  18. test: /.(png|jpg|gif|svg)$/,
  19. use: [
  20. {
  21. loader: "file-loader",
  22. options: {
  23. name: "[name].[ext]",
  24. outputPath: "images",
  25. }
  26. }
  27. ]
  28. },
  29. {
  30. test: /.(woff|woff2|eot|ttf|otf)$/,
  31. use: [
  32. {
  33. loader: "file-loader",
  34. options: {
  35. name: "[name].[ext]",
  36. outputPath: "fonts"
  37. }
  38. }
  39. ]
  40. {
  41. test: /.html$/,
  42. loader: [
  43. "html-loader"
  44. ]
  45. }
  46. }
  47. ]
  48. }

还有bable-loader ,url-loader, postcss-loader,less-loader,vue-loader,sass-loader等等

WebPack的怎么动态生成html并插入资源文件(css,js)?

</>复制代码

  1. return new HtmlWebpackPlugin({
  2. filename: `${fileName}.html`,
  3. template: "./template.html",
  4. inject: true,
  5. chunks: [`${fileName}`, "vendor"],
  6. minify: {
  7. collapseWhitespace: true,
  8. removeComments: true,
  9. useShortDoctype: true,
  10. trimCustomFragments: true,
  11. removeTagWhitespace: true,
  12. removeStyleLinkTypeAttributes: true,
  13. removeScriptTypeAttributes: true,
  14. removeRedundantAttributes: true
  15. }
  16. });

使用HtmlWebpackPlugin

WebPack怎么tree-shake?

</>复制代码

  1. 使用 ES2015 模块语法(即 importexport)。 确保没有 compiler 将 ES2015 模块语法转换为CommonJS 模块(这也是流行的 Babel preset 中 @babel/preset-env 的默认行为 - 更多详细信息请查看 文档)。 在项目 package.json 文件中,添加一个 "sideEffects" 属性。 通过将 mode 选项设置为production,启用 minification(代码压缩) 和 tree shaking。

WebPack怎么设置模块热更新?

</>复制代码

  1. devServer: {
  2. contentBase: "./dist",
  3. compress: true,
  4. hot: true
  5. },

使用webpack-dev-middlemare webpack-hot-middlemare
server端

</>复制代码

  1. const express = require("express");
  2. const webpack = require("webpack");
  3. const app = express();
  4. const webpackConfig = require("./webpack.config");
  5. const compiler = webpack(webpackConfig);
  6. app.use(require("webpack-dev-middleware")(compiler, {
  7. noInfo: true,
  8. publicPath: webpackConfig.output.publicPath
  9. }));
  10. app.use(require("webpack-hot-middleware")(compiler));
  11. app.listen(3000, () => {
  12. console.log(3000);
  13. });

webpack entry配置

</>复制代码

  1. const hotMiddlewareScript = "webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000&reload=true";
  2. {
  3. index: ["hotMiddlewareScript", "./index.js"]
  4. }

Talk is cheap. Show me the code

安装Webpack环境

</>复制代码

  1. mkdir learn-webpack && cd learn-webpack
  2. npm init -y
  3. npm install webpack webpack-cli --save-dev
  4. touch webpack.config.js

webpack.config.js :

</>复制代码

  1. const path = require("path");
  2. const { CleanWebpackPlugin } = require("clean-webpack-plugin");
  3. const HtmlWebpackPlugin = require("html-webpack-plugin");
  4. const MiniCssExtractPlugin = require("mini-css-extract-plugin");
  5. const webpack = require("webpack");
  6. const glob = require("glob");
  7. const TerserJSPlugin = require("terser-webpack-plugin");
  8. const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin");
  9. const getEntries = () => {
  10. return glob
  11. .sync("src/**/*.js")
  12. .map(url => `./${url}`);
  13. };
  14. const getEntryNames = () => {
  15. const PRE_STR = "./src/";
  16. const entries = {};
  17. getEntries()
  18. .forEach(url => {
  19. const removeExtUrl = url.replace(/.js$/ig, "");
  20. const fileParamsWithPath = removeExtUrl.slice(PRE_STR.length).split("/");
  21. entries[fileParamsWithPath.join("-")] = url.replace(/.js$/, "");
  22. });
  23. return entries;
  24. };
  25. console.log(getEntryNames());
  26. const getWebpackHtmls = () => {
  27. const PRE_STR = "./src/";
  28. return getEntries()
  29. .map(url => {
  30. const removeExtUrl = url.replace(/.js$/ig, "");
  31. const fileParamsWithPath = removeExtUrl.slice(PRE_STR.length).split("/");
  32. const fileName = fileParamsWithPath.join("-");
  33. return new HtmlWebpackPlugin({
  34. filename: `${fileName}.html`,
  35. template: "./template.html",
  36. inject: true,
  37. chunks: [`${fileName}`, "vendor"],
  38. minify: {
  39. collapseWhitespace: true,
  40. removeComments: true,
  41. useShortDoctype: true,
  42. trimCustomFragments: true,
  43. removeTagWhitespace: true,
  44. removeStyleLinkTypeAttributes: true,
  45. removeScriptTypeAttributes: true,
  46. removeRedundantAttributes: true
  47. }
  48. });
  49. });
  50. };
  51. module.exports = {
  52. entry: getEntryNames(),
  53. output: {
  54. filename: "static/[name].js",
  55. path: path.resolve(__dirname, "dist"),
  56. publicPath: "/",
  57. chunkFilename: "static/vendor.js"
  58. },
  59. optimization: {
  60. minimizer: [new TerserJSPlugin({}), new OptimizeCSSAssetsPlugin({})],
  61. splitChunks: {
  62. name: "vendor",
  63. chunks: "all",
  64. minChunks: 1
  65. }
  66. },
  67. mode: "production",
  68. module: {
  69. rules: [
  70. {
  71. test: /.css$/,
  72. use: [
  73. {
  74. loader: MiniCssExtractPlugin.loader,
  75. options: {
  76. // you can specify a publicPath here
  77. // by default it uses publicPath in webpackOptions.output
  78. hmr: process.env.NODE_ENV === "development",
  79. },
  80. },
  81. "css-loader"
  82. ]
  83. },
  84. {
  85. test: /.(png|jpg|gif|svg)$/,
  86. use: [
  87. {
  88. loader: "file-loader",
  89. options: {
  90. name: "[name].[ext]",
  91. outputPath: "images",
  92. }
  93. }
  94. ]
  95. },
  96. {
  97. test: /.(woff|woff2|eot|ttf|otf)$/,
  98. use: [
  99. {
  100. loader: "file-loader",
  101. options: {
  102. name: "[name].[ext]",
  103. outputPath: "fonts"
  104. }
  105. }
  106. ]
  107. },
  108. {
  109. test: /.html$/,
  110. loader: [
  111. "html-loader"
  112. ]
  113. }
  114. ]
  115. },
  116. plugins: [
  117. new CleanWebpackPlugin({
  118. dry: false,
  119. dangerouslyAllowCleanPatternsOutsideProject: true
  120. }),
  121. ...getWebpackHtmls(),
  122. new MiniCssExtractPlugin({
  123. // Options similar to the same options in webpackOptions.output
  124. // both options are optional
  125. filename: "style/[name].css",
  126. chunkFilename: "style/[id].css",
  127. }),
  128. new webpack.ProvidePlugin({
  129. join: ["lodash", "join"]
  130. })
  131. ],
  132. resolve: {
  133. alias: {
  134. "@": path.resolve("./src")
  135. },
  136. extensions: [".js", ".jsx", ".css", ".less", ".json", "scss", ".vue"]
  137. }
  138. };

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/105498.html

相关文章

  • Webpack包教包会

    摘要:是什么本质上,是一个现代应用程序的静态模块打包器。当处理应用程序时,它会递归地构建一个依赖关系图,其中包含应用程序需要的每个模块,然后将所有这些模块打包成一个或多个。通过将选项设置为,启用代码压缩和。 Webpack是什么? 本质上,webpack 是一个现代 JavaScript 应用程序的静态模块打包器(module bundler)。当 webpack处理应用程序时,它会递归地构...

    gaara 评论0 收藏0
  • 前端学习资源

    摘要:提供了完整的环境,并且支持自定义域名指向,动态计算资源调整,可以完成各种应用的开发编译与部署。 react 新特性 react16 Context 算法相关 图解排序算法(二)之希尔排序 微信小程序 微信小程序组件化的解决方案移动端尺寸基本知识 浏览器 前端必读:浏览器内部工作原理浏览器缓存原理解读浏览器加载css和js及dom解析之间的关系浏览器缓存 CSS学习 移动web开发布局入...

    zhisheng 评论0 收藏0
  • 优秀博文收藏(不定期更新)

    摘要:我的书签我的书签谨慎导入,小心覆盖工具类版本管理快速切换源配置教程指南可视化工具前端工具集前端助手网络封包截取工具格式化工具标注工具模拟请求类深入浅出布局你所不知道的动画技巧与细节常用代码黑魔法小技巧,让你少写不必要的,代码更优雅一劳永 我的书签 我的书签(谨慎导入,小心覆盖) 工具类 nvm: node版本管理 nrm: 快速切换npm源 shell: zsh+on-my-zsh配...

    sunsmell 评论0 收藏0
  • 优秀博文收藏(不定期更新)

    摘要:我的书签我的书签谨慎导入,小心覆盖工具类版本管理快速切换源配置教程指南可视化工具前端工具集前端助手网络封包截取工具格式化工具标注工具模拟请求类深入浅出布局你所不知道的动画技巧与细节常用代码黑魔法小技巧,让你少写不必要的,代码更优雅一劳永 我的书签 我的书签(谨慎导入,小心覆盖) 工具类 nvm: node版本管理 nrm: 快速切换npm源 shell: zsh+on-my-zsh配...

    zhangfaliang 评论0 收藏0

发表评论

0条评论

harriszh

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<