浅浅学习复习一下webpack

作者分享了个人对webpack的学习方法,主张通过实际操作从零搭建项目来学习。文中提供了webpack4的配置示例,包括entry、output、module、resolve、plugins等关键部分,并涉及到如babel-loader、MiniCssExtractPlugin、HtmlWebpackPlugin等插件的使用。还提到了在开发和生产环境中的不同配置,以及代码压缩和静态资源处理策略。
摘要由CSDN通过智能技术生成

webpack浅浅学习复习

对于webpack学习,我个人觉得还是自己手动去从零开始搭建框架,然后进行webpack得学习比较好,然后在用于项目内,因为学习得过程中,跟使用得过程中总会不一样得,实际过程中,会遇到各种问题。

这次还是用得是webpack4得,webpack5看了,但都差不多,只是优化算法得改变,和一些属性。在之前作者也曾提过webpack5.0旨在减少配置的复杂度,使其更容易上手(webpack4的时候也说了这句话)

直接看我配置吧,看代码注释就好了,码字太烦了。
在这里插入图片描述
对于package.json
在这里插入图片描述

utils

const path = require('path') //node自带路径

exports.resolve = (dir) => path.resolve(__dirname, dir) // 相对位置转换绝对位置

exports.assetsPath = (_path) => path.posix.join("static", _path)

webpack.base.conf.js

const utils = require("./utils")
const path = require('path')
const CopyWebpackPlugin = require('copy-webpack-plugin')// 处理static下面的静态文件
const MiniCssExtractPlugin = require("mini-css-extract-plugin"); // css单独文件
const WebpackBar = require('webpackbar'); // 美化webpack控制台输出内容
const isDev = process.env.NODE_ENV === 'development'

module.exports = {
  entry: { // 入口
    app: ['./src/index.js']
  },
  output: {// 出口
    path: utils.resolve('../dist'),
    filename: 'static/js/[name]_[hash:6].js',
    publicPath: isDev ? '/' : './', // 打包后资源访问公共路径前缀 
    chunkFilename: 'static/js/[name].[chunkhash:5].chunk.js',
  },
  module: {// 模块
    rules: [
      {
        test: /\.(js|jsx|ts|tsx)$/,//一个匹配loaders所处理的文件的拓展名的正则表达式,这里用来匹配js和jsx文件(必须)
        exclude: /node_modules/,//屏蔽不需要处理的文件(文件夹)(可选)
        use: {
          loader: 'babel-loader',
          options: {  //用babel-loader需要把es6->es5
            presets: [
              '@babel/preset-env',
              ['@babel/preset-react', { runtime: "automatic" }],  //yarn add @babel/core @babel/preset-react -D
              '@babel/preset-typescript'
            ],
            plugins: [
              '@babel/plugin-proposal-class-properties',
              // '@babel/plugin-syntax-dynamic-import'
            ]
          }
        }
      },
      {
        test: /\.css$/,
        use: [isDev ? 'style-loader' : {
          loader: MiniCssExtractPlugin.loader,
          options: {
            publicPath: '../../'
          }
        }
        , {
          loader: 'css-loader',
          options: {
            sourceMap: true,
          }
        },
        {
          loader: 'postcss-loader',
          options: {
            postcssOptions: {
              plugins: [
                require('autoprefixer')
              ]
            }
          }
        },
        ]
      },
      {
        test: /\.less$/,
        exclude:/\.module\.less$/,
        use: [isDev ? 'style-loader' : {
          loader: MiniCssExtractPlugin.loader,
          options: {
            publicPath: '../../' //解决打包图片路径不对
          }
        },
        {
          loader: 'css-loader',
        },
        {
          loader: 'postcss-loader',
          options: {
            postcssOptions: {
              plugins: [
                require('autoprefixer')
              ]
            }
          }
        },
        {
          loader: 'less-loader',
        },
        ]
      },
      {
        test: /\.module\.less$/,
        use: [isDev ? 'style-loader' : {
          loader: MiniCssExtractPlugin.loader,
          options: {
            publicPath: '../../'
          }
        },
        {
          loader: 'css-loader',
          options: {
            sourceMap: true,
            modules: {
              localIdentName: isDev ? '[path]_[name]__[local]_[hash:base64:5]' : '[local]_[hash:base64:5]', // 模块化css修改样式名称
            }
          }
        },
        {
          loader: 'postcss-loader',
          options: {
            postcssOptions: {
              plugins: [
                require('autoprefixer')
              ]
            }
          }
        },
        {
          loader: 'less-loader',
          options: {
            lessOptions: {
              module: true
            },
            sourceMap: true,
          }
        },
        {
          loader: 'style-resources-loader',
          options: {
            patterns: [utils.resolve('../src/styles/index.less')]// 全局样式文件 可以用全局变量样式和mixins等
          }
        }
        ]
      },
      {
        test: /\.(png|jpe?g|svg|gif|mp3)$/,
        loader: 'url-loader',  // 这里是loader 写use要报错
        options: {
          limit: 10000, // url-loader 包含file-loader,这里不用file-loader, 小于10000B的图片base64的方式引入,大于10000B的图片以路径的方式导入
          name: 'static/img/[name].[hash:7].[ext]'
        }
      },
      {
        test: /\.(woff2?|eot|ttf|otf)$/,
        loader: 'url-loader', // 这里是loader 写use要报错
        options: {
          limit: 10000, // url-loader 包含file-loader,这里不用file-loader, 小于10000B的图片base64的方式引入,大于10000B的图片以路径的方式导入
          name: 'static/fonts/[name].[hash:7].[ext]'
        }
      },
    ]
  },
  resolve: {
    extensions: ['.js', '.json', '.jsx', '.ts', '.tsx'], // 解析扩展。(当我们通过路导入文件,找不到改文件时,会尝试加入这些后缀继续寻找文件)
    alias: {
      '@': path.join(__dirname, '..', "src"), // 在项目中使用@符号代替src路径,导入文件路径更方便
    }
  },
  plugins: [// 插件
    new CopyWebpackPlugin([
      {
        from: utils.resolve('../static'),  // 从哪个目录copy
        to: ".", // copy到那个目录
      }
    ]),
    new MiniCssExtractPlugin({
      filename: utils.assetsPath('css/[name]_[hash:7].css'),
      chunkFilename: utils.assetsPath('css/[id]_[chunkhash:7].css'),
      ignoreOrder: true
    }),
    new WebpackBar()
  ],

}

webpack.dev.conf.js

const webpackMerge = require('webpack-merge') // 合并webpack配置
const baseConfig = require('./webpack.base.conf')
const utils = require('./utils')
const HtmlWebpackPlugin = require('html-webpack-plugin') // 解析html
const portfinder = require('portfinder');//自动查找可用端口
const FriendlyErrorsWebpackPlugin = require("friendly-errors-webpack-plugin");//识别某些类的webpack错误,并清除,汇总和优先处理它们
const devWebpackConfig = webpackMerge(baseConfig, {
  plugins: [ // 插件
    new HtmlWebpackPlugin({
      filename: utils.resolve('../dist/index.html'), // html模板的生成路径
      template: './public/index.html', // 模板
      favicon: "./public/favicon.ico",
      inject: true, // true:默认值,script标签位于html文件的 body 底部
    }),
  ],
  stats: 'errors-warnings', // 控制台输出内容
  devtool: 'inline-source-map',
  devServer: {// 开发环境配置
    historyApiFallback: true, // 当找不到路径的时候,默认加载index.html文件
    hot: true,
    contentBase: false, // 告诉服务器从哪里提供内容。只有在你想要提供静态文件时才需要
    // compress: true, //一切服务器都用gzip
    inline: true,
    port: 5500, // 端口
    publicPath: '/', // 前缀
    open: true, // true,打开默认浏览器
    host: "localhost", //设置本地url
    overlay: { // 错误全屏显示
      errors: true,
      warnings: false
    },
    proxy: {
      // // 接口请求代理
      // "/api": {
      //   secure: false,
      //   target: "http://127.0.0.1:8082"
      // }
    },
  }
})
module.exports = new Promise((resolve, reject) => {
  portfinder.basePort = devWebpackConfig.devServer.port;
  portfinder.getPort((err, port) => {
    if (err) {
      reject(err)
    } else {
      process.env.PORT = port
      devWebpackConfig.devServer.port = port
      devWebpackConfig.plugins.push(
        new FriendlyErrorsWebpackPlugin({
          compilationSuccessInfo: {
            messages: [
              `Your application is running here: http://${devWebpackConfig.devServer.host}:${port}`
            ],
            notes: []
          },
          clearConsole: true
        })
      )

      resolve(devWebpackConfig)
    }
  })
})

webpack.prod.conf.js

const HtmlWebpackPlugin = require("html-webpack-plugin") // 解析html文件
const utils = require("./utils") // 导入公共方法
const webpackMerge = require('webpack-merge') // 合并webpack配置
const baseConfig = require('./webpack.base.conf')
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin; //打包完成,可视化查看每个文件大小
const { CleanWebpackPlugin } = require('clean-webpack-plugin'); // 每次打包清理文件
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin'); // 压缩css
const UglifyJsPlugin = require('uglifyjs-webpack-plugin'); // 压缩js
const CompressionWebpackPlugin = require('compression-webpack-plugin')//压缩为gizp

module.exports = webpackMerge(baseConfig, {
  plugins: [ // 插件
    new HtmlWebpackPlugin({
      filename: utils.resolve('../dist/index.html'), // html模板生成路径
      template: './public/index.html', // 模板
      favicon: "./public/favicon.ico",
      inject: true, // true 默认值 script标签位于body底部
      hash: true, // 打包资源插入html加上hash
      // html文件压缩
      minify: {
        removeComments: true, // 去除注释
        collapseWhitespace: true, // 压缩空间
        removeAttributeQuotes: true // 去除属性 标签的 引号  例如 <p id="test" /> 输出 <p id=test/>
      }
    }),
    new CompressionWebpackPlugin({
      asset: '[path].gz[query]',
      algorithm: 'gzip',
      deleteOriginalAssets: true,
      test: /\.(js|css|json|txt|html|ico|svg)(\?.*)?$/i,
      deleteOriginalAssets: true,
      threshold: 10240,
      minRatio: 0.8
     }),
    new BundleAnalyzerPlugin(),
    new CleanWebpackPlugin(),
  ],

  optimization: { // 优化
    splitChunks: {
      chunks: 'async',//表示哪些代码需要优化,有三个可选值:initial(初始块)、async(按需加载块)、all(全部块),默认为 async
      minSize: 30000,//表示在压缩前的最小模块大小
      maxSize: 0,
      minChunks: 1,//表示被引用次数
      maxAsyncRequests: 5,//按需加载时候最大的并行请求数
      maxInitialRequests: 3,// 一个入口最大的并行请求数
      automaticNameDelimiter: '~',
      name: true,
      cacheGroups: {//缓存组。缓存组的属性除上面所有属性外
        vendors: {
          test: /[\\/]node_modules[\\/]/,
          priority: -10
        },
        commons: {
          test: /[\\/]node_modules[\\/]/,
          name: 'vendors',
          chunks: 'all',
        },
        default: {
          minChunks: 2,
          priority: -20,
          reuseExistingChunk: true
        }
      }
    },
    minimizer: [  // 压缩css
      new UglifyJsPlugin({
        parallel: true,  //使用多进程并行运行来提高构建速度
        cache: true, // Boolean/String,字符串即是缓存文件存放的路径
        uglifyOptions: {
          warnings: false,
          output: {
            comments: false,   // 使输出的代码尽可能紧凑
            beautify: false  // 输出删掉所有注释
          },
          compress: {
            drop_console: true, // 过滤console,即使写了console,线上也不显示
            drop_debugger: true,
            // warnings:false// UglifyJs版本跟这个没对应上
          }
        }
      }),
      new OptimizeCSSAssetsPlugin({
        assetNameRegExp: /\.(less)|(css)$/g,
        cssProcessor: require('cssnano'), // 用这个压缩过后更小
        cssProcessorOptions: {
          safe: true,
          discardComments: { removeAll: true }, // 移除注释
          normalizeUnicode: false // 建议false,否则在使用unicode-range的时候会产生乱码
        },
        canPrint: true
      }),
    ]
  },
})

然后这是我练习得一个demo
在这里插入图片描述
通过自己练习比别人讲得要很多,别人讲得再好也是别人得,毕竟笨鸟在于勤于补拙。

参考:掘金

demo地址:github

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值