webpack5基础+vue-cli配置

3,808 阅读6分钟

webpack前端资源构建工具,当 webpack 处理应用程序时,会递归构建一个依赖关系图,其中包含应用程序需要的每个模块,然后将这些模块打包成一个或多个 bundle

webpack五个核心概念

1.entry:入口,提示webpack从哪个文件开始打包,分析构建内部依赖图。
2.output:输出,提示webpack打包后的资源bundles输出到那个文件去,以及如何命名。
3.loader:翻译,由于webpack只认识js文件,所以需要loader将非js,json文件转化为webpack认识的文件。
4.plugins:插件,插件可以用于执行范围更广的任务,从打包优化和压缩,一直到重新定义环境中的变量等。
5.mode:模式,开发和生产(优化压缩)

webpack安装

使用 npm init -y 进行初始化(也可以使用 yarn)。

安装 webpackwebpack-cli
命令:npm install webpack webpack-cli -D

webpack.config.js基础配置(开发)

处理css样式文件

//已安装所需loader,处理css,less文件
const { resolve } = require("path"); //resolve用来拼接绝对路径的方法
module.exports = {
  entry: "./src/index.js",

  output: {
    filename: "built.js",
    path: resolve(__dirname, "build"), //__dirname表示当前文件的绝对路径,__dirname是node.js的变量。
  },

  module: {
    rules: [
      //   loader配置
      {
        test: /\.css$/,
        use: [
          //执行顺序从后往前
          "style-loader",
          "css-loader",
        ],
      },
      {
        test: /\.less$/,
        use: [
          //执行顺序从后往前
          "style-loader",
          "css-loader",
          "less-loader"
        ],
      },
    ],
  },

  plugins: [],

  mode: "development",
};

处理html文件

//先下载html-webpack-plugi插件,引入,使用。
const { resolve } = require("path"); //resolve用来拼接绝对路径的方法
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
  entry: "./src/index.js",

  output: {
    filename: "built.js",
    path: resolve(__dirname, "build"), //__dirname表示当前文件的绝对路径,__dirname是node.js的变量。
  },

  module: {
    rules: [
      //   loader配置
      {
        test: /\.css$/,
        use: [
          //执行顺序从后往前
          "style-loader",
          "css-loader",
        ],
      },
      {
        test: /\.less$/,
        use: [
          //执行顺序从后往前
          "style-loader",
          "css-loader",
          "less-loader",
        ],
      },
    ],
  },

  plugins: [new HtmlWebpackPlugin({ template: "./src/index.html" })],

  mode: "development",
};

处理图片资源

const { resolve } = require("path"); //resolve用来拼接绝对路径的方法
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
  entry: "./src/index.js",

  output: {
    filename: "built.js",
    path: resolve(__dirname, "build"), //__dirname表示当前文件的绝对路径,__dirname是node.js的变量。
    clean: true, //清空build目录的方式
  },

  module: {
    rules: [
      //   loader配置
      {
        test: /\.css$/,
        use: [
          //执行顺序从后往前
          "style-loader",
          "css-loader",
        ],
      },
      {
        test: /\.less$/,
        use: [
          //执行顺序从后往前
          "style-loader",
          "css-loader",
          "less-loader",
        ],
      },
      // {
      //   test: /\.(jpg|png|gif)$/,
      //   loader: "url-loader",      // 下载url-loader file-loader
      //   options: {
      //     // 图片小于8kb就会转为base64
      //     // 优点是减少请求数量(减轻服务器压力)
      //     // 缺点是图片体积会更大(请求速度会变慢)
      //     limit: 8 * 1024,
      //   },
      // },
      {
        test: /\.(jpe?g|png|gif)$/i,
        type: "asset",
        generator: {
          filename: "static/[name].[hash].[ext]",
        },
      },
      //如果需要处理html中的图片则需要用到[html-loader]`npm i  html-loader -D`
      {
        test: /\.html$/i,
        loader: "html-loader",
      },
    ],
  },

  plugins: [new HtmlWebpackPlugin({ template: "./src/index.html" })],

  mode: "development",
};

处理其他资源(原封不动输出)

const { resolve } = require("path"); //resolve用来拼接绝对路径的方法
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
  entry: "./src/index.js",

  output: {
    filename: "built.js",
    path: resolve(__dirname, "build"), //__dirname表示当前文件的绝对路径,__dirname是node.js的变量。
    clean: true, //清空build目录的方式
  },

  module: {
    rules: [
      //   loader配置
      {
        test: /\.css$/,
        use: [
          //执行顺序从后往前
          "style-loader",
          "css-loader",
        ],
      },
      {
        test: /\.less$/,
        use: [
          //执行顺序从后往前
          "style-loader",
          "css-loader",
          "less-loader",
        ],
      },
      // {
      //   test: /\.(jpg|png|gif)$/,
      //   loader: "url-loader",      // 下载url-loader file-loader
      //   options: {
      //     // 图片小于8kb就会转为base64
      //     // 优点是减少请求数量(减轻服务器压力)
      //     // 缺点是图片体积会更大(请求速度会变慢)
      //     limit: 8 * 1024,
      //   },
      // },
      {
        test: /\.(jpe?g|png|gif)$/i,
        type: "asset",
        // limit:25 * 1024,                        
        generator: {
          filename: "static/[name].[hash].[ext]",
        },
      },
      {
        test: /\.html$/i,
        loader: "html-loader",
      },
      //排除掉已经匹配过(已经处理的)的文件,然后直接输出
      {
        exclude:/\.(css|less|js|html)$/,
        loader:'file-loader'
      }
    ],
  },

  plugins: [new HtmlWebpackPlugin({ template: "./src/index.html" })],

  mode: "development",
};

开发服务器devServer

安装webpack-dev-server:npm intall webpack-dev-server -D

启动命令:npx webpack serve

const { resolve } = require("path"); //resolve用来拼接绝对路径的方法
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
  entry: "./src/index.js",

  output: {
    filename: "built.js",
    path: resolve(__dirname, "build"), //__dirname表示当前文件的绝对路径,__dirname是node.js的变量。
    clean: true, //清空build目录的方式
  },

  module: {
    rules: [
      //   loader配置
      {
        test: /\.css$/,
        use: [
          //执行顺序从后往前
          "style-loader",
          "css-loader",
        ],
      },
      {
        test: /\.less$/,
        use: [
          //执行顺序从后往前
          "style-loader",
          "css-loader",
          "less-loader",
        ],
      },
      // {
      //   test: /\.(jpg|png|gif)$/,
      //   loader: "url-loader",      // 下载url-loader file-loader
      //   options: {
      //     // 图片小于8kb就会转为base64
      //     // 优点是减少请求数量(减轻服务器压力)
      //     // 缺点是图片体积会更大(请求速度会变慢)
      //     limit: 8 * 1024,
      //   },
      // },
      {
        test: /\.(jpe?g|png|gif)$/i,
        type: "asset",
        // limit:25 * 1024,                        
        generator: {
          filename: "static/[name].[hash].[ext]",
        },
      },
      {
        test: /\.html$/i,
        loader: "html-loader",
      },
      // {
      //   exclude:/\.(css|less|js|html)$/,
      //   loader:'file-loader'
      // }
    ],
  },

  plugins: [new HtmlWebpackPlugin({ template: "./src/index.html" })],

  mode: "development",

//启动一个开发服务器,用来自动化(自动编译,自动刷新浏览器)
  devServer:{
    static:resolve(__dirname, "build"), //项目构建后的路径
    compress:true,  //启动gzip压缩
    port:3000,  
    open:true
  }
};

webpack.config.js基础配置(生产)

css文件处理(输出为单独文件,兼容,压缩)

const { resolve } = require("path"); //resolve用来拼接绝对路径的方法
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const OptimizeCssAssetsWebpackPlugin = require("optimize-css-assets-webpack-plugin");

process.env.NODE_ENV = "development"; //不设置默认是生产

module.exports = {
  entry: "./src/index.js",

  output: {
    filename: "built.js",
    path: resolve(__dirname, "build"), //__dirname表示当前文件的绝对路径,__dirname是node.js的变量。
    clean: true, //清空build目录的方式
  },

  module: {
    rules: [
      //   loader配置
      {
        test: /\.css$/,
        use: [
          //执行顺序从后往前
          // "style-loader",
          MiniCssExtractPlugin.loader, //提取css为单独文件
          "css-loader",
          {
            loader: "postcss-loader",
            options: {
              postcssOptions: {
                //帮助postcss找到package.json中的browserslist里面的配置,加载指定的css兼容性样式
                plugins: ["postcss-preset-env"],
              },
            },
          },
        ],
      },

      {
        test: /\.(jpe?g|png|gif)$/i,
        type: "asset",
        
        generator: {
          filename: "static/[name].[hash].[ext]",
        },
      },
      {
        test: /\.html$/i,
        loader: "html-loader",
      },
    ],
  },

  plugins: [
    new HtmlWebpackPlugin({ template: "./src/index.html" }),
    new MiniCssExtractPlugin({ filename: "css/built.css" }),
    new OptimizeCssAssetsWebpackPlugin(), //压缩css
  ],

  mode: "development",

  devServer: {
    static: resolve(__dirname, "build"), //项目构建后的路径
    compress: true, //启动gzip压缩
    port: 3000,
    open: true,
  },
};

eslint格式检查

//package.json文件
"eslintConfig": {
    "extends": "airbnb-base"
  }
  
  
const { resolve } = require("path"); //resolve用来拼接绝对路径的方法
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const OptimizeCssAssetsWebpackPlugin = require("optimize-css-assets-webpack-plugin");
process.env.NODE_ENV = "development"; //不设置默认是生产

module.exports = {
  entry: "./src/index.js",

  output: {
    filename: "built.js",
    path: resolve(__dirname, "build"), //__dirname表示当前文件的绝对路径,__dirname是node.js的变量。
    clean: true, //清空build目录的方式
  },

  module: {
    rules: [
      //   loader配置
      {
        test: /\.css$/,
        use: [
          //执行顺序从后往前
          // "style-loader",
          MiniCssExtractPlugin.loader, //提取css为单独文件
          "css-loader",
          {
            loader: "postcss-loader",
            options: {
              postcssOptions: {
                //帮助postcss找到package.json中的browserslist里面的配置,加载指定的css兼容性样式
                plugins: ["postcss-preset-env"],
              },
            },
          },
        ],
      },
      {
        test: /\.(jpe?g|png|gif)$/i,
        type: "asset",
        // limit:25 * 1024,
        generator: {
          filename: "static/[name].[hash].[ext]",
        },
      },
      {
        test: /\.html$/i,
        loader: "html-loader",
      },
      //eslint-disable-next-line
      //语法检查:eslint eslint-loader eslint-config-airbnb-base eslint-plugin-import
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: "eslint-loader",
        options: {
          fix: true, //自动修复
        },
      },
    ],
  },

  plugins: [
    new HtmlWebpackPlugin({ template: "./src/index.html" }),
    new MiniCssExtractPlugin({ filename: "css/built.css" }),
    new OptimizeCssAssetsWebpackPlugin(), //压缩css
  ],

  mode: "development",

  devServer: {
    static: resolve(__dirname, "build"), //项目构建后的路径
    compress: true, //启动gzip压缩
    port: 3000,
    open: true,
  },
};

html压缩js兼容es6...

const { resolve } = require("path"); //resolve用来拼接绝对路径的方法
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const OptimizeCssAssetsWebpackPlugin = require("optimize-css-assets-webpack-plugin");

process.env.NODE_ENV = "development"; //不设置默认是生产

module.exports = {
  entry: "./src/index.js",

  output: {
    filename: "built.js",
    path: resolve(__dirname, "build"), //__dirname表示当前文件的绝对路径,__dirname是node.js的变量。
    clean: true, //清空build目录的方式
  },

  module: {
    rules: [
      //   loader配置
      {
        test: /\.css$/,
        use: [
          //执行顺序从后往前
          // "style-loader",
          MiniCssExtractPlugin.loader, //提取css为单独文件
          "css-loader",
          {
            loader: "postcss-loader",
            options: {
              postcssOptions: {
                //帮助postcss找到package.json中的browserslist里面的配置,加载指定的css兼容性样式
                plugins: ["postcss-preset-env"],
              },
            },
          },
        ],
      },
      {
        test: /\.(jpe?g|png|gif)$/i,
        type: "asset",
        // limit:25 * 1024,
        generator: {
          filename: "static/[name].[hash].[ext]",
        },
      },
      {
        test: /\.html$/i,
        loader: "html-loader",
      },
      //eslint-disable-next-line
      //语法检查:eslint eslint-loader eslint-config-airbnb-base eslint-plugin-import
      // {
      //   test: /\.js$/,
      //   exclude: /node_modules/,
      //   loader: "eslint-loader",
      //   options: {
      //     fix: true, //自动修复
      //   },
      // },

    //js兼容处理babel-loader @babel/core @babel/preset-env(基本兼容处理)core-js(按需兼容)
     
      {
        test: /\.js$/,
        // exclude: /node_modules/,
        loader: "babel-loader",
        options: {
          presets: [
            "@babel/preset-env",
            //指定corejs的版本
          {  
            useBuiltIns:UsageState,
            corejs:{version:3},
            targets:{
              chrome:'60',
              firefox:'60',
              ie:'9',
              safsri:'10',
              edge:'17'
            }
          }
            
          ],
        },
      },


    ],
  },

  plugins: [
    new HtmlWebpackPlugin({   
      template: "./src/index.html",
      minify: {                   //html压缩
        collapseWhitespace: true, //移除空格
        removeComments: true, //移除注释
      },
    }),
    new MiniCssExtractPlugin({ filename: "css/built.css" }),
    new OptimizeCssAssetsWebpackPlugin(), //压缩css
  ],


  mode: "development",

  devServer: {
    static: resolve(__dirname, "build"), //项目构建后的路径
    compress: true, //启动gzip压缩
    port: 3000,
    open: true,
  },
};

vue项目中webpack配置vue.config.js

Vue.js CLI工具 不知不觉发展到了4.0时代,CLI给人最直白的感受是没有了build文件夹跟config文件夹,所有的配置都在Vue.config.js完成。

有三种方式,推荐第二种标准版(无需安装依赖,直接复制即可配置)。

1、依赖库
npm install vue-cli-configjs
2、标准版
// vue.config.js
const path =  require('path');
const IS_PROD = ['production', 'prod'].includes(process.env.NODE_ENV);
const resolve = (dir) => path.join(__dirname, dir);
module.exports = {
    publicPath: process.env.NODE_ENV === 'production' ? '/site/vue-demo/' : '/',  // 公共路径
    indexPath: 'index.html' , // 相对于打包路径index.html的路径
    outputDir: process.env.outputDir || 'dist', // 'dist', 生产环境构建文件的目录
    assetsDir: 'static', // 相对于outputDir的静态资源(js、css、img、fonts)目录
    lintOnSave: false, // 是否在开发环境下通过 eslint-loader 在每次保存时 lint 代码
    runtimeCompiler: true, // 是否使用包含运行时编译器的 Vue 构建版本
    productionSourceMap: !IS_PROD, // 生产环境的 source map
    parallel: require("os").cpus().length > 1, // 是否为 Babel 或 TypeScript 使用 thread-loader。该选项在系统的 CPU 有多于一个内核时自动启用,仅作用于生产构建。
    pwa: {}, // 向 PWA 插件传递选项。
    chainWebpack: config => {
        config.resolve.symlinks(true); // 修复热更新失效
        // 如果使用多页面打包,使用vue inspect --plugins查看html是否在结果数组中
        config.plugin("html").tap(args => {
            // 修复 Lazy loading routes Error
            args[0].chunksSortMode = "none";
            return args;
        });
        config.resolve.alias // 添加别名
            .set('@', resolve('src'))
            .set('@assets', resolve('src/assets'))
            .set('@components', resolve('src/components'))
            .set('@views', resolve('src/views'))
            .set('@store', resolve('src/store'));
    },
    css: {
        extract: IS_PROD,
        requireModuleExtension: false,// 去掉文件名中的 .module
        loaderOptions: {
                // 给 less-loader 传递 Less.js 相关选项
                less: {
                    // `globalVars` 定义全局对象,可加入全局变量
                    globalVars: {
                        primary: '#333'
                    }
                }
        }
    },
    devServer: {
            overlay: { // 让浏览器 overlay 同时显示警告和错误
              warnings: true,
              errors: true
            },
            host: "localhost",
            port: 8080, // 端口号
            https: false, // https:{type:Boolean}
            open: false, //配置自动启动浏览器
            hotOnly: true, // 热更新
            // proxy: 'http://localhost:8080'   // 配置跨域处理,只有一个代理
            proxy: { //配置多个跨域
                "/api": {
                    target: "http://172.11.11.11:7071",
                    changeOrigin: true,
                    // ws: true,//websocket支持
                    secure: false,
                    pathRewrite: {
                        "^/api": "/"
                    }
                },
                "/api2": {
                    target: "http://172.12.12.12:2018",
                    changeOrigin: true,
                    //ws: true,//websocket支持
                    secure: false,
                    pathRewrite: {
                        "^/api2": "/"
                    }
                },
            }
        }
}
3、升级版
// vue.config.js
const path =  require('path');

const CompressionWebpackPlugin = require("compression-webpack-plugin"); // 开启gzip压缩, 按需引用
const productionGzipExtensions = /.(js|css|json|txt|html|ico|svg)(?.*)?$/i; // 开启gzip压缩, 按需写入
const BundleAnalyzerPlugin = require("webpack-bundle-analyzer").BundleAnalyzerPlugin; // 打包分析

const IS_PROD = ['production', 'prod'].includes(process.env.NODE_ENV);
const resolve = (dir) => path.join(__dirname, dir);
module.exports = {
    publicPath: process.env.NODE_ENV === 'production' ? '/site/vue-demo/' : '/',  // 公共路径
    indexPath: 'index.html' , // 相对于打包路径index.html的路径
    outputDir: process.env.outputDir || 'dist', // 'dist', 生产环境构建文件的目录
    assetsDir: 'static', // 相对于outputDir的静态资源(js、css、img、fonts)目录
    lintOnSave: false, // 是否在开发环境下通过 eslint-loader 在每次保存时 lint 代码
    runtimeCompiler: true, // 是否使用包含运行时编译器的 Vue 构建版本
    productionSourceMap: !IS_PROD, // 生产环境的 source map
    parallel: require("os").cpus().length > 1, // 是否为 Babel 或 TypeScript 使用 thread-loader。该选项在系统的 CPU 有多于一个内核时自动启用,仅作用于生产构建。
    pwa: {}, // 向 PWA 插件传递选项。
    chainWebpack: config => {
        config.resolve.symlinks(true); // 修复热更新失效
        // 如果使用多页面打包,使用vue inspect --plugins查看html是否在结果数组中
        config.plugin("html").tap(args => {
            // 修复 Lazy loading routes Error
            args[0].chunksSortMode = "none";
            return args;
        });
        config.resolve.alias // 添加别名
            .set('@', resolve('src'))
            .set('@assets', resolve('src/assets'))
            .set('@components', resolve('src/components'))
            .set('@views', resolve('src/views'))
            .set('@store', resolve('src/store'));
        // 压缩图片
        // 需要 npm i -D image-webpack-loader
        config.module
            .rule("images")
            .use("image-webpack-loader")
            .loader("image-webpack-loader")
            .options({
                mozjpeg: { progressive: true, quality: 65 },
                optipng: { enabled: false },
                pngquant: { quality: [0.65, 0.9], speed: 4 },
                gifsicle: { interlaced: false },
                webp: { quality: 75 }
            });
        // 打包分析
        // 打包之后自动生成一个名叫report.html文件(可忽视)
        if (IS_PROD) {
            config.plugin("webpack-report").use(BundleAnalyzerPlugin, [
                {
                    analyzerMode: "static"
                }
            ]);
        }
    },
    configureWebpack: config => {
        // 开启 gzip 压缩
        // 需要 npm i -D compression-webpack-plugin
        const plugins = [];
        if (IS_PROD) {
            plugins.push(
                new CompressionWebpackPlugin({
                    filename: "[path].gz[query]",
                    algorithm: "gzip",
                    test: productionGzipExtensions,
                    threshold: 10240,
                    minRatio: 0.8
                })
            );
        }
        config.plugins = [...config.plugins, ...plugins];
    },
    css: {
        extract: IS_PROD,
        requireModuleExtension: false,// 去掉文件名中的 .module
        loaderOptions: {
                // 给 less-loader 传递 Less.js 相关选项
                less: {
                    // `globalVars` 定义全局对象,可加入全局变量
                    globalVars: {
                        primary: '#333'
                    }
                }
        }
    },
    devServer: {
            overlay: { // 让浏览器 overlay 同时显示警告和错误
              warnings: true,
              errors: true
            },
            host: "localhost",
            port: 8080, // 端口号
            https: false, // https:{type:Boolean}
            open: false, //配置自动启动浏览器
            hotOnly: true, // 热更新
            // proxy: 'http://localhost:8080'   // 配置跨域处理,只有一个代理
            proxy: { //配置多个跨域
                "/api": {
                    target: "http://172.11.11.11:7071",
                    changeOrigin: true,
                    // ws: true,//websocket支持
                    secure: false,
                    pathRewrite: {
                        "^/api": "/"
                    }
                },
                "/api2": {
                    target: "http://172.12.12.12:2018",
                    changeOrigin: true,
                    //ws: true,//websocket支持
                    secure: false,
                    pathRewrite: {
                        "^/api2": "/"
                    }
                },
            }
        }
}