?1、基礎配置
// node js核心模塊
const path = require('path')
// 插件是需要引入使用的
const ESLintPlugin = require('eslint-webpack-plugin')
// 自動生成index.html
const HtmlWebpackPlugin = require('html-webpack-plugin');
// 將css文件單獨打包,在index.html中使用 link引入,不使用 style
// 因為 style 標簽,在網絡慢的情況下加載的時候,有可能一加載時啥也沒有,然后突然就出現東西
// 因為 style 是有js創建的, 需要等待js執行完才行,但是link不用等待
const MiniCssExtractPlugin = require("mini-css-extract-plugin")
// css 壓縮
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin")
// 引入多進程成相關的配置
const TerserWebpackPlugin = require("terser-webpack-plugin")
// 引入Cpu 相關的東西,獲取cpu核數,需要對應的安裝 thread-loader
const os = require('os')
const threads = os.cpus().lengthfunction getCssLoader(pre){return [MiniCssExtractPlugin.loader,"css-loader",{loader: "postcss-loader",options: {postcssOptions: {plugins: [["postcss-preset-env",{// Options},],],},},},pre].filter(Boolean)
}/*** webpack 優化 從下面四個角度找方法(plugins/loader 及結合其他方式)* 1、提升開發體驗* devtool: 配置 devtool: 'source-map'* 2、提升打包構建速度* 2.1、oneOf的使用* 2.2、include/exclude* 2.3、cache babel/eslint* 3、減少代碼體積* tree-shaking 去除用不上代碼,webpack 默認配置* 4、優化代碼運行性能* 4.1、code split代碼分割* 分割文件: 將打包生成的文件進行分割,生成多個js文件* 按需加載: 需要那個文件就加載那個文件 import()*/// 運營命令 npx webpack --config ./config/webpack.prod.js
module.exports = {// 入口entry: "./src/main.js",// 輸出output: {// 需要回退一下路徑,因為當前文件,不是在根目錄下path: path.resolve(__dirname, "../dist"),filename: 'static/js/main.js',// chunk 模塊命名chunkFilename: 'static/js/[name].chunk.js',// 其他公共模塊,這里是字體圖標與圖片都放一起了assetModuleFilename: "static/media/[hash:10][ext][query]",// 每次打包前都先清空distclean: true},// 加載器module: {rules:[{oneOf: [{test: /\.css$/i,use: getCssLoader(),},{test: /\.less$/i,use: getCssLoader("less-loader"),},{test: /\.s[ac]ss$/i,use: getCssLoader("sass-loader"),},{test: /\.(jpg|png|svg|jpeg)$/,type: 'asset',parser: {dataUrlCondition: {// 設置圖片小于多少kb就轉成base64 字符串// 有點事可以減少請求,缺點是內容會變大,大圖會變更大,所以大圖不轉// webpack5 內置了 file-loader 與 url-loader 但是這個轉base操作需要自己開啟maxSize: 30 * 1024 // 30kb}},// 圖片放到自己的目錄// generator: {// // hash 值保留十位// filename: 'static/image/[hash:10][ext][query]'// }},{// 處理字體圖標及媒體相關文件test: /\.(ttf|woff2?|map3|map4|avi)$/,// 小圖不轉base64, 原封不動type: 'asset/resource',// 圖片放到自己的目錄// generator: {// // hash 值保留十位// filename: 'static/media/[hash:10][ext][query]'// }},{test: /\.(?:js|mjs|cjs)$/,// include: path.resolve(__dirname, "src")exclude: /node_modules/, // 排除那些文件,這些文件不處理use: [{loader: "thread-loader",options: {// 工作的 cpu 核數works: threads}},// 對于promise 數組一些高級方法 例如 includes 有些低版本瀏覽器不兼容,需要 corejs 做處理{loader: 'babel-loader',// 這個配置一般可以在這配置,也可以在外邊使用 babel.config.js 配置// options: {// presets: [// ['@babel/preset-env', { targets: "defaults" }]// ]// }options: {// 開啟緩存,第一次,不會起作用,第二次之后,每次打包// 都只會檢查改變的那些文件cacheDirectory: true,// 不開啟緩存文件壓縮,會拖慢速度cacheCompression: false,// 減少代碼體積,因為babel會給每個js 文件添加一些輔助代碼(例如__extend函數定義)// 是用了,下面這個,所有js文件就會統一從下面這個獲取,節儉代碼體積plugins: ["@babel/plugin-transform-runtime"]}}]}]}]},// 插件plugins: [new ESLintPlugin({// 檢查那些文件// 這會會報錯,得有eslint配置文件才行, 例如 .eslintrc.jscontext: path.resolve(__dirname, "../src"),// 開啟緩存cache: true,// 緩存路徑cacheLocation: path.resolve(__dirname,"../node_modules/.cache/eslintcache"),// 開啟多進程threads,}),// 這個插件可以自動引入,打包文件new HtmlWebpackPlugin({// 以這個文件為模板,自動生成index.html 文件template: 'public/index.html'}),new MiniCssExtractPlugin({// 所有 樣式文件合成一個,多個文件的時候使用各自的名字filename: "static/css/[name].css",// 對于一些動態引入的css 模塊的打包文件名chunkFilename: "static/css/[name].chunk.css"}),],// 官方放壓縮的地方,生產才會有壓縮,開發沒有壓縮,不需要optimization: {minimizer:[// 開啟css壓縮new CssMinimizerPlugin(),// 壓縮jsnew TerserWebpackPlugin({// 開啟多進程和設置進程數量, 但是這是對于js打包比較慢的情況才合適// 否則開進程也是需要耗時的parallel: threads})],// 代碼分割配置, a.js b.js 都引入c.js 都會在a.js b.js 中引入,但是這樣配置之后就不會了// 但是打包后會多出一份文件 xx.js a ,文件下也會多出 一些引用c.js文件的代碼splitChunks: {chunks: "all", // 對所有模塊都進行分割// 以下是默認值// minSize: 20000, // 分割代碼最小的大小// minRemainingSize: 0, // 類似于minSize,最后確保提取的文件大小不能為0// minChunks: 1, // 至少被引用的次數,滿足條件才會代碼分割// maxAsyncRequests: 30, // 按需加載時并行加載的文件的最大數量// maxInitialRequests: 30, // 入口js文件最大并行請求數量// enforceSizeThreshold: 50000, // 超過50kb一定會單獨打包(此時會忽略minRemainingSize、maxAsyncRequests、maxInitialRequests)// cacheGroups: { // 組,哪些模塊要打包到一個組// defaultVendors: { // 組名// test: /[\\/]node_modules[\\/]/, // 需要打包到一起的模塊// priority: -10, // 權重(越大越高)// reuseExistingChunk: true, // 如果當前 chunk 包含已從主 bundle 中拆分出的模塊,則它將被重用,而不是生成新的模塊// },// default: { // 其他沒有寫的配置會使用上面的默認值// minChunks: 2, // 這里的minChunks權重更大// priority: -20,// reuseExistingChunk: true,// },// },// 修改配置// cacheGroups: {// 組,哪些模塊要打包到一個組// defaultVendors: { // 組名// test: /[\\/]node_modules[\\/]/, // 需要打包到一起的模塊// priority: -10, // 權重(越大越高)// reuseExistingChunk: true, // 如果當前 chunk 包含已從主 bundle 中拆分出的模塊,則它將被重用,而不是生成新的模塊// },// default: {// // 其他沒有寫的配置會使用上面的默認值// minSize: 0, // 我們定義的文件體積太小了,所以要改打包的最小文件體積// minChunks: 2,// priority: -20,// reuseExistingChunk: true,// },// },},},// 模式, 默認開啟 js 及 html 壓縮mode: 'production',// 開啟代碼映射,當代嗎出錯的時候,就可以在控制臺 有對應的出錯位置映射,具有行與列映射devtool: 'source-map'
}
corejs處理,在項目根目錄下的 babel.config.js 文件配置
module.exports = {presets: [['@babel/preset-env',{// 按需加載,自動引入,corejs 相關包useBuiltIns: "usage",corejs: 3}]]
}
2、高級優化
3、Vue腳手架 webpack配置
項目文件目錄
webpack.config.js文件
const path = require("path");
const EslintWebpackPlugin = require("eslint-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CssMinimizerWebpackPlugin = require("css-minimizer-webpack-plugin");
const TerserWebpackPlugin = require("terser-webpack-plugin");
const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
const CopyPlugin = require("copy-webpack-plugin");
const { VueLoaderPlugin } = require("vue-loader");
const { DefinePlugin } = require("webpack");
const AutoImport = require("unplugin-auto-import/webpack");
const Components = require("unplugin-vue-components/webpack");
const { ElementPlusResolver } = require("unplugin-vue-components/resolvers");const isProduction = process.env.NODE_ENV === "production";// 返回處理樣式loader函數
const getStyleLoaders = (pre) => {return [isProduction ? MiniCssExtractPlugin.loader : "vue-style-loader","css-loader",{// 處理css兼容性問題// 配合package.json中browserslist來指定兼容性loader: "postcss-loader",options: {postcssOptions: {plugins: ["postcss-preset-env"],},},},pre && {loader: pre,options:pre === "sass-loader"? {additionalData: `@use "@/styles/element/index.scss" as *;`,}: {},},].filter(Boolean);
};module.exports = {entry: "./src/main.js",output: {path: isProduction ? path.resolve(__dirname, "../dist") : undefined,filename: isProduction ? "static/js/[name].[contenthash:10].js" : "static/js/[name].js",chunkFilename: isProduction ? "static/js/[name].[contenthash:10].chunk.js" : "static/js/[name].chunk.js",assetModuleFilename: "static/media/[hash:10][ext][query]",clean: true,},module: {rules: [// 處理css{test: /\.css$/,use: getStyleLoaders(),},{test: /\.less$/,use: getStyleLoaders("less-loader"),},{test: /\.s[ac]ss$/,use: getStyleLoaders("sass-loader"),},{test: /\.styl$/,use: getStyleLoaders("stylus-loader"),},// 處理圖片{test: /\.(jpe?g|png|gif|webp|svg)$/,type: "asset",parser: {dataUrlCondition: {maxSize: 10 * 1024,},},},// 處理其他資源{test: /\.(woff2?|ttf)$/,type: "asset/resource",},// 處理js{test: /\.js$/,include: path.resolve(__dirname, "../src"),loader: "babel-loader",options: {cacheDirectory: true,cacheCompression: false,},},{test: /\.vue$/,loader: "vue-loader",options: {// 開啟緩存cacheDirectory: path.resolve(__dirname, "../node_modules/.cache/vue-loader"),},},],},// 處理htmlplugins: [new EslintWebpackPlugin({context: path.resolve(__dirname, "../src"),exclude: "node_modules",cache: true,cacheLocation: path.resolve(__dirname, "../node_modules/.cache/.eslintcache"),}),new HtmlWebpackPlugin({template: path.resolve(__dirname, "../public/index.html"),}),isProduction &&new MiniCssExtractPlugin({filename: "static/css/[name].[contenthash:10].css",chunkFilename: "static/css/[name].[contenthash:10].chunk.css",}),isProduction &&new CopyPlugin({patterns: [{from: path.resolve(__dirname, "../public"),to: path.resolve(__dirname, "../dist"),globOptions: {// 忽略index.html文件ignore: ["**/index.html"],},},],}),new VueLoaderPlugin(),// cross-env定義的環境變量給打包工具使用// DefinePlugin定義環境變量給源代碼使用,從而解決vue3頁面警告的問題new DefinePlugin({__VUE_OPTIONS_API__: true,__VUE_PROD_DEVTOOLS__: false,}),// 按需加載element-plusAutoImport({resolvers: [ElementPlusResolver()],}),Components({resolvers: [ElementPlusResolver({// 自定義主題,引入sassimportStyle: "sass",}),],}),].filter(Boolean),mode: isProduction ? "production" : "development",devtool: isProduction ? "source-map" : "cheap-module-source-map",optimization: {splitChunks: {chunks: "all",cacheGroups: {vue: {test: /[\\/]node_modules[\\/]vue(.*)?[\\/]/,name: "vue-chunk",priority: 40,},elementPlus: {test: /[\\/]node_modules[\\/]element-plus[\\/]/,name: "elementPlus-chunk",priority: 30,},libs: {test: /[\\/]node_modules[\\/]/,name: "libs-chunk",priority: 20,},},},runtimeChunk: {name: (entrypoint) => `runtime~${entrypoint.name}.js`,},minimize: isProduction,minimizer: [new CssMinimizerWebpackPlugin(),new TerserWebpackPlugin(),new ImageMinimizerPlugin({minimizer: {implementation: ImageMinimizerPlugin.imageminGenerate,options: {plugins: [["gifsicle", { interlaced: true }],["jpegtran", { progressive: true }],["optipng", { optimizationLevel: 5 }],["svgo",{plugins: ["preset-default","prefixIds",{name: "sortAttrs",params: {xmlnsOrder: "alphabetical",},},],},],],},},}),],},// webpack解析模塊加載選項resolve: {// 自動補全文件擴展名extensions: [".vue", ".js", ".json"],// 路徑別名alias: {"@": path.resolve(__dirname, "../src"),},},devServer: {host: "localhost",port: 3000,open: true,hot: true, // 開啟HMRhistoryApiFallback: true, // 解決前端路由刷新404問題},performance: false,
};
.eslintrc.js 文件
module.exports = {root: true,env: {node: true,},extends: ["plugin:vue/vue3-essential", "eslint:recommended"],parserOptions: {parser: "@babel/eslint-parser",},
};
babel.config.js文件
module.exports = {presets: ["@vue/cli-plugin-babel/preset"],
};
記錄學習 webpack 的過程