经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » JS/JS库/框架 » JavaScript » 查看文章
Webpack 5 配置手册(从0开始)
来源:cnblogs  作者:heyaiyang  时间:2021/3/29 9:09:24  对本文有异议

针对新手入门搭建项目,Webpack5 配置手册(从0开始)

webpack安装顺序

  1. 1. `npm init -y`,初始化包管理文件 package.json
  2. 2. 新建src源代码目录
  3. 3. 新建index.html
  4. 4. `yarn add webpack webpack-cli`,安装webpack相关包
  5. 5. 在项目根目录中,创建webpack.config.js 的配置文件
  6. 6. `yarn add webpack-dev-server`,安装支持项目自动打包的工具,并配置
  7. 7. `yarn add html-webpack-plugin`,安装生成预览页面插件并配置
  8. 8. `yarn add style-loader css-loader`,安装处理css文件的loader
  9. 9. `yarn add less-loader less`,安装处理less文件的loader
  10. 10. `yarn add sass-loader node-sass`,安装处理scss文件的loader
  11. 11. `yarn add postcss postcss-loader postcss-preset-env autoprefixer`,配置postCSS自动添加css的兼容前缀(可选)
  12. 12. `yarn add url-loader file-loader`,安装处理css文件中的图片和字体文件
  13. 13. `yarn add html-loader`,安装处理html文件中的图片和字体文件
  14. 14. `yarn add @babel/core babel-loader @babel/preset-env 前面3个是必须的,后面的看需要 @babel/plugin-transform-runtime @babel/plugin-proposal-class-properties`,安装处理js高级语法(ES6以上)
  15. 15. 之后看下面的插件安装代码。
  1. yarn add html-webpack-plugin
  2. yarn add style-loader css-loader
  3. yarn add less-loader less
  4. yarn add sass-loader node-sass
  5. yarn add url-loader file-loader
  6. yarn add html-loader
  7. yarn add @babel/core babel-loader @babel/preset-env 前面3个是必须的,后面的看需要 @babel/plugin-transform-runtime @babel/plugin-proposal-class-properties
  8. yarn add postcss postcss-loader postcss-preset-env
  9. yarn add mini-css-extract-plugin
  10. yarn add optimize-css-assets-webpack-plugin
  11. yarn add eslint eslint-loader eslint-webpack-plugin
  12. yarn add eslint-config-airbnb-base eslint-config-airbnb vueeslint
  13. yarn add clean-webpack-plugin

使用npx babel-upgrade将所有关于babel的插件都升级都最新版本以适应兼容性

在.babelrc 中配置,或者在package.json中直接添加

  1. {
  2. "presets": ["@babel/preset-env"],
  3. "plugins": [
  4. "@babel/plugin-transform-runtime",
  5. "@babel/plugin-proposal-class-properties"
  6. ]
  7. }

webpack.config.js中配置插件

  1. const path = require('path');
  2. const htmlWebpackPlugin = require('html-webpack-plugin');
  3. const { CleanWebpackPlugin } = require('clean-webpack-plugin');
  4. module.exports = {
  5. mode: 'development',
  6. entry: path.join(__dirname, './src/main.js'),
  7. output: {
  8. path: path.join(__dirname, './dist'),
  9. filename: 'bundle.js',
  10. },
  11. // 插件
  12. plugins: [
  13. // html
  14. new htmlWebpackPlugin({
  15. template: path.join(__dirname, './src/index.html'),
  16. filename: 'index.html',
  17. }),
  18. // 打包前清除dist
  19. new CleanWebpackPlugin(),
  20. ],
  21. // Loaders 部分
  22. module: {
  23. rules: [
  24. {
  25. // test设置需要匹配的文件类型,支持正则
  26. test: /\.css$/,
  27. // use表示该文件类型需要调用的loader
  28. use: ['style-loader', 'css-loader'],
  29. },
  30. {
  31. test: /\.less$/,
  32. use: ['style-loader', 'css-loader', 'less-loader'],
  33. },
  34. {
  35. test: /\.scss$/,
  36. use: ['style-loader', 'css-loader', 'sass-loader'],
  37. },
  38. {
  39. test: /\.(png|gif|bmp|jpg)$/,
  40. use: {
  41. loader: 'url-loader',
  42. options: {
  43. limit: 8 * 1024,
  44. // 图片取10位hash和文件扩展名
  45. name: '[hash:10].[ext]',
  46. // 关闭es6模块化
  47. esModule: false,
  48. // 图片资源的输出路径
  49. outputPath: 'images',
  50. },
  51. },
  52. },
  53. // 处理html中img资源
  54. {
  55. test: /.\html$/,
  56. loader: "html-loader"
  57. },
  58. // 处理其他资源(一般指的就是字体资源等)
  59. // {
  60. // exclude: /\.(html|js|css|less|scss|jpg|png|gif)/,
  61. // loader: "file-loader",
  62. // outputPath:'media'
  63. // },
  64. {
  65. test: /\.(woff(2)?|eot|ttf|otf|svg|)$/,
  66. type: 'asset/inline',
  67. },
  68. {
  69. test: /\.js/,
  70. exclude: /node_modules/,
  71. use: {
  72. loader: 'babel-loader',
  73. options: {
  74. presets: ['@babel/preset-env'],
  75. plugins: ['@babel/plugin-proposal-class-properties'],
  76. },
  77. },
  78. },
  79. ],
  80. },
  81. // 使用webpck-dev-server时配置
  82. devServer: {
  83. historyApiFallback: true,
  84. contentBase: path.join(__dirname, './dist'),
  85. open: true,
  86. hot: true,
  87. quiet: true,
  88. port: 3000,
  89. },
  90. };

webpack.config.js中配置插件

  1. const { resolve } = require('path');
  2. const MiniCssExtractPlugin = require('mini-css-extract-plugin');
  3. const OptimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin');
  4. const HtmlWebpackPlugin = require('html-webpack-plugin');
  5. const ESLintPlugin = require('eslint-webpack-plugin');
  6. // 导入每次删除文件夹的插件
  7. const { CleanWebpackPlugin } = require('clean-webpack-plugin');
  8. // 复用loader加载器
  9. const commonCssLoader = [
  10. MiniCssExtractPlugin.loader,
  11. 'css-loader',
  12. // css兼容性处理
  13. // 还需要在package.json中定义browserlist
  14. 'postcss-loader'
  15. // 下面是根据路径找配置文件
  16. // {
  17. // loader: 'postcss-loader',
  18. // options: {
  19. // postcssOptions:{
  20. // config:'./postcss.config.js'
  21. // }
  22. // }
  23. // }
  24. ];
  25. // 定义node.js到环境变量,决定使用browserslist的哪个环境
  26. process.env.NODE_ENV = 'production';
  27. module.exports = {
  28. entry: './src/main.js',
  29. output: {
  30. filename: 'js/bundle.js',
  31. path: resolve(__dirname, 'dist')
  32. },
  33. module: {
  34. rules: [
  35. {
  36. test: /\.css$/,
  37. use: [
  38. ...commonCssLoader,
  39. ]
  40. },
  41. {
  42. test: /\.less$/,
  43. use: [
  44. ...commonCssLoader,
  45. 'less-loader'
  46. ]
  47. },
  48. // {
  49. // // eslint语法检查,在package.json中eslintConfig --> airbnb的校验规则
  50. // test: /\.js$/,
  51. // exclude: /node_modules/,
  52. // // 优先执行,先执行eslint在执行babel
  53. // enforce: 'pre',
  54. // loader: 'eslint-loader',
  55. // options: {
  56. // fix: true
  57. // }
  58. // },
  59. {
  60. // js代码兼容性处理
  61. test: /\.js$/,
  62. exclude: /node_modules/,
  63. loader: 'babel-loader',
  64. options: {
  65. presets: [
  66. ['@babel/preset-env', //基础预设
  67. {
  68. useBuiltIns: 'usage', // 按需加载
  69. corejs: {
  70. version: 3
  71. },
  72. targets: {
  73. // 兼容到什么版本到浏览器
  74. chrome: '60',
  75. firefox: '50',
  76. ie: '9',
  77. safari: '10',
  78. edge: '17'
  79. }
  80. }
  81. ]],
  82. plugins: ['@babel/transform-runtime','@babel/plugin-proposal-class-properties'],
  83. }
  84. },
  85. {
  86. test: /\.(png|gif|bmp|jpg)$/,
  87. use: {
  88. loader: 'url-loader',
  89. options: {
  90. limit: 8 * 1024,
  91. // 图片取10位hash和文件扩展名
  92. name: '[hash:10].[ext]',
  93. // 关闭es6模块化
  94. esModule: false,
  95. // 图片资源的输出路径
  96. outputPath: 'images',
  97. // publicPath : 这个则是生成的页面中对图片路径的引用时,加上publicPath。
  98. publicPath: "../images"
  99. }
  100. }
  101. },
  102. // 处理html中img资源
  103. {
  104. test: /.\html$/,
  105. loader: 'html-loader'
  106. },
  107. // 处理其他?件
  108. {
  109. exclude: /\.(js|css|less|html|jpg|png|gif)/,
  110. loader: 'file-loader',
  111. options: { outputPath: 'media', },
  112. },
  113. ]
  114. },
  115. plugins: [
  116. // css代码单独抽离
  117. new MiniCssExtractPlugin({
  118. filename: 'css/bundle.css'
  119. }),
  120. // css代码压缩
  121. new OptimizeCssAssetsWebpackPlugin(),
  122. // html文件压缩
  123. new HtmlWebpackPlugin({
  124. template: './src/index.html',
  125. minify: {
  126. // 移除空格
  127. collapseWhitespace: true,
  128. // 移除注释
  129. removeComments: true
  130. }
  131. }),
  132. // new ESLintPlugin({
  133. // exclude:'node_modules',
  134. // fix:true
  135. // }),
  136. new CleanWebpackPlugin(),
  137. ]
  138. ,
  139. mode: 'production'
  140. };

postcss.config.js配置

  1. module.exports = {
  2. // You can specify any options from https://postcss.org/api/#processoptions here
  3. // parser: 'sugarss',
  4. plugins: [
  5. // Plugins for PostCSS
  6. // ["postcss-short", { prefix: "x" }],
  7. "postcss-preset-env",
  8. ],
  9. };

.eslintlrc.js配置

  1. module.exports = {
  2. root: true,
  3. env: {
  4. commonjs: true,
  5. es6: true,
  6. browser: true,
  7. node: true
  8. },
  9. extends: [
  10. "airbnb-base",
  11. // 'plugin:vue/essential',
  12. // '@vue/standard'
  13. ],
  14. parserOptions: {
  15. ecmaVersion: 7,
  16. ecmaFeatures: {
  17. jsx: true,
  18. experimentalObjectRestSpread: true,
  19. },
  20. parser: 'babel-eslint',
  21. sourceType: "module"
  22. },
  23. rules: {
  24. 'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
  25. 'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off'
  26. }
  27. }

.gitignore配置

  1. node_modules/*
  2. package-lock.json
  3. dist/*
  4. .idea/*

package.json配置

  1. {
  2. "scripts": {
  3. "test": "echo \"Error: no test specified\" && exit 1",
  4. "serve": "webpack serve",
  5. "dev": "webpack --config webpack.config.js",
  6. "build": "webpack --config webpack.pub.config.js"
  7. },
  8. "browserslist": {
  9. "development": [
  10. "last 1 chrome version",
  11. "last 1 firefox version",
  12. "last 1 safari version"
  13. ],
  14. "production": [
  15. ">0.2%",
  16. "not dead",
  17. "not op_mini all"
  18. ]
  19. }
  20. }

遇到的问题

  1. 开发环境,热部署devServer的重新配置,在webpack.config.js中添加热部署的部分代码,之后在package.json
    文件内scripts中配置相应的webpack
  2. 生产环境在package.json中的配置"build": "webpack --config webpack.pub.config.js"
  3. 生产环境图片资源打包之后,网页显示不出来,需要在图片资源的打包中添加publicPath: "../images",这个
    则是生成的页面中对图片路径的引用时,加上publicPath,这样访问时姐可以放到文件的正确地址了。
  4. css代码的兼容性处理,使用postcss-loader的配置,可以直接在use里加载postcss-loader的配置文件,也可以直接
    使用postcss-loader,让后打包时自动在根目录中找postcss.confgi.js配置文件,来加载postcss配置,此项目使用的
    外部postcss.confgi.js配置文件的配置方式。注意:还需要在package.json中定义browserlist
  5. 另外:目前还有生产环境懒加载和eslint校验代码的功能未完成,eslint的校验遇到问题class Person { static info = { name: 'zs' }; },在生产环境的webpack.pub.config.js中引入来插件eslint-webpack-plugin,配置了new ESLintPlugin(),
    但是提示错误信息如下,Parsing error: Unexpected token =

gitee 仓库地址

https://gitee.com/heyhaiyon/webpack5-config

原文链接:http://www.cnblogs.com/heyhaiyang/p/14459583.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号