chaihongjun.me

一个简单的webpack5配置

安装的开发依赖:

"devDependencies": {
    "@babel/core": "^7.15.0",
    "@babel/polyfill": "^7.12.1",
    "@babel/preset-env": "^7.15.0",
    "autoprefixer": "^10.3.1",
    "babel-loader": "^8.2.2",
    "clean-webpack-plugin": "^4.0.0-alpha.0",
    "core-js": "^3.16.1",
    "css-loader": "^6.2.0",
    "css-minimizer-webpack-plugin": "^3.0.2",
    "file-loader": "^6.2.0",
    "html-loader": "^2.1.2",
    "html-webpack-plugin": "^5.3.2",
    "image-minimizer-webpack-plugin": "^2.2.0",
    "imagemin-gifsicle": "^7.0.0",
    "imagemin-jpegtran": "^7.0.0",
    "imagemin-optipng": "^8.0.0",
    "imagemin-svgo": "^9.0.0",
    "jpegtran-bin": "^5.0.2",
    "less-loader": "^10.0.1",
    "mini-css-extract-plugin": "^2.2.0",
    "postcss": "^8.3.6",
    "postcss-loader": "^6.1.1",
    "style-loader": "^3.2.1",
    "swiper": "^3.4.1",
    "url-loader": "^4.1.1",
    "webpack": "^5.49.0",
    "webpack-cli": "^4.7.2",
    "webpack-dev-server": "^3.11.2",
    "webpack-merge": "^5.8.0"
  },
  "browserslist": [
    "> 1%",
    "last 2 versions"
  ],

CSS厂商兼容:

module.exports = {
  plugins: [
    require('autoprefixer')
  ],
};

webpack公共配置:

const { resolve } = require('path');
// const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
// const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
// const StylelintPlugin = require('stylelint-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
// const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
// 通用Style Loader
const CommonStyleLoader = [
  MiniCssExtractPlugin.loader,
  'css-loader',
  'postcss-loader',
]
module.exports = {
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: resolve(__dirname, 'dist')
  },
  module: {
    rules: [
      // 使用资源模块处理字体
      {
        test: /.(eot|svg|ttf|woff|woff2)$/i,
        type: 'asset/resource',
        generator: {
          filename: 'fonts/[name].[hash:5][ext]'

        }
      },
      //处理CSS
      {
        test: /.css$/,
        use: CommonStyleLoader
      },
      // 处理Less
      {
        test: /.less$/,
        use: [
          // 'style-loader',
          ...CommonStyleLoader,
          'less-loader'
        ]
      },
      // 资源模块处理图片
      {
        test: /.(png|jpe?g|gif)$/i,
        type: "asset",
        parser: {
          dataUrlCondition: {
            maxSize: 8 * 1024 // 8kb
          }
        },
        generator: {
          // filename: 'images/[name].[hash:5][ext]'
          filename: 'images/[name][ext]'
        }
      },
      // 打包html中的图片
      // {
      //   test: /.html$/,
      //   loader: "html-loader",
      //   options: {
      //     minimize: false,
      //     esModule: false,
      //   }
      // },
      // 编译JS
      {
        test: /.m?js$/,
        exclude: /(node_modules|bower_components)/, //排除本地需要编译的目录
        use: {
          loader: 'babel-loader',
          options: {
            presets: [
              [
                "@babel/preset-env",
                {
                  //按需转换JS
                  useBuiltIns: "usage",
                  // corejs 版本
                  corejs: 3,
                  targets: "defaults",
                }
              ]
            ]
          }
        }
      }
    ]
  },
  plugins: [
    // 打包前 清理输出目录
    new CleanWebpackPlugin(),
    //提取CSS到单独的CSS文件
    new MiniCssExtractPlugin({
      filename: "style/[name].[hash:5].css",
    }),
    // new StylelintPlugin({
    //   //指定检查源文件所在目录
    //   files: ["./src/style/*.(css|less)"]
    // }),
  ],

  devServer: {
    contentBase: resolve(__dirname, 'dist'),
    host: 'localhost',  // 配置启动ip地址
    port: 9090,  // 配置端口
    open: true, // 配置是否自动打开浏览器
    compress: true,
    liveReload: true, //热更新
    //配置代理 解决跨域
    proxy: {
      // http://localhost:8080/api
      "/api": {    // 这里的`/api`是自定义的
        // http://localhost:8080/api/users = >  https://api.github.com/api/users
        target: "https://api.github.com/", //这里是真实的接口baseURL
        //http://localhost:8080 => https://api.github.com
        changeOrigin: true,
        ws: true,
        secure: false,
        pathRewrite: {
          //去掉 '/api/'
          // http://localhost:8080/api/users = >  https://api.github.com/users
          "^/api": "", // 这里的`^/api`也是是自定义的
        },
      },
    }
  },
  target: 'web', //热更新
}

webpack开发配置:

const { resolve } = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { merge } = require('webpack-merge');
// 引入基本配置
const baseWebpackConfig = require('./webpack.base.config.js')
const devWebpackConfig = merge(baseWebpackConfig, {
  //这里是开发环境配置内容
  mode: "development",
  plugins: [
    //打包HTML页面
    new HtmlWebpackPlugin({
      // title: 'webpack5',
      template: './src/index.ejs',
      filename: 'index.html',
      // meta: {
      //   keywords: '关键词'
      // },
    }),
  ],
  // devServer: {
  //   contentBase: resolve(__dirname, 'dist'),
  //   host: 'localhost',  // 配置启动ip地址
  //   port: 9090,  // 配置端口
  //   open: true, // 配置是否自动打开浏览器
  //   compress: true,
  //   liveReload: true, //热更新
  //   //配置代理 解决跨域
  //   proxy: {
  //     // http://localhost:8080/api
  //     "/api": {    // 这里的`/api`是自定义的
  //       // http://localhost:8080/api/users = >  https://api.github.com/api/users
  //       target: "https://api.github.com/", //这里是真实的接口baseURL
  //       //http://localhost:8080 => https://api.github.com
  //       changeOrigin: true,
  //       ws: true,
  //       secure: false,
  //       pathRewrite: {
  //         //去掉 '/api/'
  //         // http://localhost:8080/api/users = >  https://api.github.com/users
  //         "^/api": "", // 这里的`^/api`也是是自定义的
  //       },
  //     },
  //   }
  // },
  // target: 'web', //热更新
})
// 最后通过 module.exports 导出
module.exports = devWebpackConfig

webpack生产配置:

const HtmlWebpackPlugin = require('html-webpack-plugin');
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const { merge } = require('webpack-merge');
// 引入基本配置
const baseWebpackConfig = require('./webpack.base.config.js')
const prodWebpackConfig = merge(baseWebpackConfig, {
  //这里是生产环境配置内容
  mode: "production",
  optimization: {
    minimize: true,   //优化CSS
    minimizer: [
      new CssMinimizerPlugin({
        parallel: true,  //使用多进程并发执行,提升构建速度
      }),
    ]
  },
  plugins: [
    // 打包前 清理输出目录
    new CleanWebpackPlugin(),
    // //提取CSS到单独的CSS文件
    // new MiniCssExtractPlugin({
    //   filename: "style/[name].[hash:5].css",
    // }),
    // new StylelintPlugin({
    //   //指定检查源文件所在目录
    //   files: ["./src/style/*.(css|less)"]
    // }),
    // 图片压缩
    new ImageMinimizerPlugin({
      minimizerOptions: {
        // Lossless optimization with custom option
        // Feel free to experiment with options for better result for you
        plugins: [
          ["gifsicle", { interlaced: true }],
          ["jpegtran", { progressive: true }],
          ["optipng", { optimizationLevel: 5 }],
        ],
      },
      filter: (source, sourcePath) => {
        if (source.byteLength < 8 * 1024) { //小于8Kb不优化
          return false;
        }
        return true;
      },
    }),

    //打包HTML页面
    new HtmlWebpackPlugin({
      // title: 'webpack5',
      template: './src/index.ejs',
      filename: 'index.html',
      meta: {
        keywords: '关键词'
      },
      // 压缩html页面 开发环境不需要
      minify: {
        collapseWhitespace: true,
        keepClosingSlash: true,
        removeComments: true,
        removeRedundantAttributes: true,
        removeScriptTypeAttributes: true,
        removeStyleLinkTypeAttributes: true,
        useShortDoctype: true
      }
    }),
  ]
})
// 最后通过 module.exports 导出
module.exports = prodWebpackConfig

调试脚本:

  "scripts": {
    "build:dev": "webpack --config webpack.dev.config.js",
    "build:prod": "webpack --config webpack.prod.config.js",
    "serve": "webpack serve --config webpack.dev.config.js",
}


知识共享许可协议本作品采用知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议进行许可。作者:chaihongjun»

相关推荐