国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

Webpack5 基本使用 - 2

這篇具有很好參考價(jià)值的文章主要介紹了Webpack5 基本使用 - 2。希望對(duì)大家有所幫助。如果存在錯(cuò)誤或未考慮完全的地方,請(qǐng)大家不吝賜教,您也可以點(diǎn)擊"舉報(bào)違法"按鈕提交疑問。

常用 loader

  • loader 是輔助打包工具。
  • webpack 默認(rèn)只能打包 js 文件,打包其它模塊就需要配置 loader 來告訴 webpack 該怎么去打包其它文件。
  • loader 可以將文件從不同的語言轉(zhuǎn)換為 JavaScript
  • 一類文件如果需要多個(gè) loader 處理,loader 的執(zhí)行順序是從后往前。

打包樣式文件

打包 css

css 文件需要先用 css-loader 處理,再用 style-loader 插入 <style></style>標(biāo)簽中。

安裝 css-loader、style-loader

yarn add css-loader style-loader --save
module.exports = {
	module: {
		rules: [
			{
				test: /\.css$/,
				use: [
					// 再用 style-loader 創(chuàng)建 style 標(biāo)簽插入 <head></head> 標(biāo)簽中
					'style-loader',
					// css 文件需要先用 css-loader 處理,將 css 編譯成 commonjs 整合到 js 中
					'css-loader'
				]
			}
		]
	}
};
// 使用 localIdentName 自定義生成的樣式名稱格式,可選的參數(shù)有: 
// [path] 表示樣式表相對(duì)于項(xiàng)目根目錄所在路徑 
// [name] 表示樣式表文件名稱 
// [local] 表示樣式的類名定義名稱 
// [hash:length] 表示32位的hash值 

module.exports = {
	module: {
		rules: [
			{
				test: /\.css$/,
				use: [
					'style-loader',
					{
						loader: 'css-loader',
						options: {
							modules: {
								localIdentName: '[path][name]-[local]'
							}
						}
					}
				]
			}
		]
	}
};
// index.js
import add from '@utils/add';
import './css/style.css';

// import styles from './css/style.css';
// console.log(styles);

console.log(add(1, 4));
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1 class="title">hello webpack5</h1>
</body>
</html>

Webpack5 基本使用 - 2,前端,webpack,軟件構(gòu)建

樣式兼容性處理

postcss-loader 自動(dòng)添加瀏覽器前綴。

使用 autofixer 插件輔助

autoprefixer 可以指定需要兼容的瀏覽器。

安裝 postcss-loader、autofixer

yarn add postcss-loader autoprefixer --save
// 通過配置加載指定的 css 兼容性樣式
// postcss-loader 在 css-loader 之前調(diào)用
module.exports = {
	module: {
		rules: [
			{
				test: /\.scss$/,
				use: [
					'style-loader',
					'css-loader',
					{
						loader: 'postcss-loader',
						options: {
							postcssOptions: {
								plugins: [
									[
										'autoprefixer', 
										{
											// options
											// 直接在這里指定瀏覽器版本
											overrideBrowsersList: ['last 5 versions']
										}
									]
								]
							}
						}
					},
					'sass-loader'
				]
			}
		]
	}
};
使用 postcss-preset-env 插件輔助

postcss-preset-env 插件可以指定需要添加的瀏覽器。

安裝 postcss-loader、postcss-preset-env

yarn add postcss-loader postcss-prest-env --save
// 通過配置加載指定的css兼容性樣式
module.exports = {
	module: {
		rules: [
			{
				test: /\.scss$/,
				use: [
					'style-loader',
					'css-loader',
					{
						loader: 'postcss-loader',
						options: {
						    postcssOptions: {
								plugins: [
									[
					                    "postcss-preset-env",
					                    {
					                      // Options
					                      "browserslist": {
												"development": [
													// 兼容最近的一個(gè) chrome 的版本
													"last 1 chrome version",
													"last 1 firefox version",
													"last 1 safari version",
												],
												"production": [
													// 大于 99.8% 的瀏覽器
													">0.2%",
													// 不要已經(jīng)死了的瀏覽器:比如 IE10,兼容沒有意義
													"not dead",
													// op_mini 的瀏覽器全都死亡了
													"not op_mini all"
												]
											}
					                    },
				                  	]
								]
							}
						}
					},
					'sass-loader'
				]
			},
			{
				test: /\.scss$/,
				use: [
					'style-loader',
					'css-loader',
					{
						loader: 'postcss-loader',
						// 寫法二
						options: {
							ident: 'postcss',
							plugins: [
								require('postcss-preset-env')()
							]
						}
					},
					'sass-loader'
				]
			}
		]
	}
};
打包 less

安裝 less、less-loader、css-loader、style-loader

yarn add less less-loader css-loader style-loader --save
module.exports = {
	module: {
		rules: [
			// less-loader 是基于 less 的,所以使用 less-loader 需要同時(shí)安裝 less
			{
				test: /\.less$/,
				use: [
					'style-loader',
					'css-loader',
					'less-loader'
				]
			}
		]
	}
};

打包 sass

安裝 sass、sass-loader、css-loader、style-loader

yarn add sass sass-loader css-loader style-loader --save
module.exports = {
	module: {
		rules: [
			// sass-loader 是基于 sass 的,所以使用 sass-loader 需要同時(shí)安裝 sass
			{
				test: /\.scss$/,
				use: [
					'style-loader',
					'css-loader',
					'postcss-loader',
					'sass-loader'
				]
			}
		]
	}
};
打包 styl

安裝 stylus-loader、style-loader、css-loader'

yarn add stylus-loader css-loader style-loader
module.exports = {
	module: {
		rules: [
			{
				test: /\.scss$/,
				use: [
					'style-loader',
					'css-loader',
					'postcss-loader',
					'stylus-loader'
				]
			}
		]
	}
};

打包圖片、字體等靜態(tài)資源

打包圖片

webpack4 需要使用url-loaderfile-loader,webpack5 已內(nèi)置,使用模塊 asset。

asset/resource
  • 使用 asset/resource 處理的資源會(huì)輸出到目錄中,采用哈希命名
  • file-loaderwebpack5 中已被 asset/resource 替代。
module.exports = {
	module: {
		rules: [
			{
				test: /\.(png|jpeg|gif|PNG)$/,
				type: 'asset/resource'
			}
		]
	}
};

Webpack5 基本使用 - 2,前端,webpack,軟件構(gòu)建

Webpack5 基本使用 - 2,前端,webpack,軟件構(gòu)建

const path = require('path');

module.exports = {
  output: {
    // ...
    // 指定所有 assetModule 文件的輸出目錄,同時(shí)重命名輸出的文件名稱
   	// assetModuleFilename: 'static/[hash][ext][query]'
  },
  module: {
    rules: [
      {
        test: /\.(png|jpg|jpeg|gif|PNG)$/,
        type: 'asset/resource',
        generator: {
        	// 與 assetModuleFilename 只取其一
			// 輸出圖片的名稱
			filename: 'images/[hash:8][ext][query]'
		}
     }
    ]
  },
};

Webpack5 基本使用 - 2,前端,webpack,軟件構(gòu)建

asset/inline
  • url-loaderwebpack5 中已被 asset/inline 替換。
  • 打包輸出的數(shù)據(jù) URI 使用 Base64 算法編碼的文件內(nèi)容(可以減少 http 請(qǐng)求數(shù)量,但是體積會(huì)變大)
module.exports = {
	module: {
		rules: [
			{
				test: /\.(png|jpg|jpeg|gif|PNG)$/,
				type: 'asset/inline'
			}
		]
	}
};
asset
module.exports = {
	module: {
		output: {
			// ...
			// 指定 assetModule 文件的輸出目錄,同時(shí)重命名輸出的文件名稱
        	// assetModuleFilename: 'images/[hash:8][ext][query]'
		},
		rules: [
			{
				test: /\.(png|jpeg|gif|PNG)$/,
				type: 'asset',
				parser: {
					// 自定義轉(zhuǎn) base64 的界限
					dataUrlCondition: {
						// 小于 10kb 的圖片轉(zhuǎn) base64
						maxSize: 10 * 1024 // 10kb
					}
				},
				generator: {
					// 跟 assetModuleFilename 之中選一個(gè)即可
					// 輸出圖片的名稱
					filename: 'images/[hash:8][ext][query]'
				}
			}
		]
	}
};
打包字體圖標(biāo)資源
module.exports = {
	module: {
		output: {
			// ...
			// 指定圖片文件的輸出目錄,同時(shí)重命名輸出的文件名稱
        	// assetModuleFilename: 'fonts/[hash:8][ext][query]'
		},
		rules: [
			{
				test: /\.(ttf|otf|woff2?)$/,
				type: 'asset',
				generator: {
					// 跟 assetModuleFilename 之中選一個(gè)即可
					// 輸出文件的名稱
					filename: 'fonts/[hash:8][ext][query]'
				}
			}
		]
	}
};
打包其他資源
module.exports = {
	module: {
		output: {
			// ...
			// 指定圖片文件的輸出目錄,同時(shí)重命名輸出的文件名稱
        	// assetModuleFilename: 'media/[hash:8][ext][query]'
		},
		rules: [
			{
				test: /\.(mp3|mp4|avi|excel)$/,
				type: 'asset',
				generator: {
					// 跟 assetModuleFilename 之中選一個(gè)即可
					// 輸出文件的名稱
					filename: 'media/[hash:8][ext][query]'
				}
			}
		]
	}
};

js 兼容性處理

因?yàn)椴皇撬袨g覽器都能識(shí)別 es6 語法,所以需要通過 babel 進(jìn)行轉(zhuǎn)換,將 es6 語法轉(zhuǎn)換成所有瀏覽器都可以識(shí)別的 es5 語法。

使用最新版本 babel

最新版本 babel 已支持轉(zhuǎn)換 generator 函數(shù),以及最新的 es6 語法。

安裝 babel-loader、@babel/core、@babel/preset-env

yarn add babel-loader @babel/core @babel/preset-env -D
module.exports = {
	module: {
		rules: [
			{
				test: /\.js$/,
				loader: 'babel-loader',
				exclude: /mode_modules/
			}
		]
	}
};
// 新建 .babelrc 文件
{
    "presets": ["@babel/preset-env"],
    "plugins": []
}
轉(zhuǎn)換 jsx 語法
  • 使用 @babel/preset-react
  • 或者使用 @babel/preset-env 、 @babel/react

方法一:安裝 @babel/preset-env 、 @babel/react

{
	presets: [
        '@babel/preset-env',
        '@babel/react'
    ],
    plugins: []
}

方法二:安裝 @babel/preset-react

{
	presets: ['@babel/preset-react'],
    plugins: []
}
使用低版本 babel
轉(zhuǎn)換基本語法

安裝 babel-loader、@babel/core、@babel/preset-env

module.exports = {
	module: {
		rules: [
			{
				test: /\.js$/,
				loader: 'babel-loader',
				exclude: /mode_modules/,
				// 第一種配置,在這里通過 options 配置預(yù)設(shè)
				options: {
					// 預(yù)設(shè):指示babel做什么樣的兼容性處理
					presets: '@babel/preset-env'
				}
			}
		]
	}
};
// 第二種配置:新建 .babelrc 文件
{
    "presets": ["@babel/preset-env"],
    "plugins": []
}
  • @babel/preset-env 不能轉(zhuǎn)換所有的 es6 語法(比如 async await 、generator 函數(shù)),只能轉(zhuǎn)換基本語法;
  • 最新版本的已支持,如要測試請(qǐng)使用低版本 babel
@babel/pollyfill
  • @babel/pollyfill 相當(dāng)于 babel 的補(bǔ)丁,使用 @babel/pollyfill 可以轉(zhuǎn)換所有語法。

  • @babel/pollyfillcore-jsregenerator 的集合(推薦單獨(dú)安裝 core-jsregenerator ,因?yàn)?code>@babel/pollyfill 會(huì)污染全局變量)

  • @babel/pollyfillbabel 7.4.0 以后已被棄用,如果想測試,需要安裝低版本 babel 測試。

  • 引入 @babel/pollyfill 可以做 js 全部兼容性處理

  • 會(huì)將所有的兼容性代碼全部引入,體積太大,而且會(huì)污染全局變量

// 在需要處理的文件中通過 import 引入
import '@babel/pollyfill';
按需加載
  • 使用 core-js 可以解決 @babel/pollyfill 全部引入,導(dǎo)致體積太大的問題。
  • core-js@babel/pollyfill 不能同時(shí)使用,只安裝一個(gè)即可, @babel/pollyfill 內(nèi)置有 core-js。

安裝 core-js

// .babelrc
{
    "presets": [
        [
            "@babel/preset-env",
            {
                // 按需加載
                "useBuiltIns": "usage",
                // 指定 core-js 版本
                "corejs": 3
            }
        ]
    ],
    "plugins": []
}
babel-runtime
  • babel-runtime 可以解決 @babel/pollyfill 污染全局變量的問題。

安裝 @babel/plugin-transform-runtime@babel/runtime

yarn add @babel/plugin-transform-runtime -D
yarn add @babel/runtime --save
// .babelrc
{
    "presets": [
        [
            "@babel/preset-env",
            {
                // 按需加載
                "useBuiltIns": "usage",
                // 指定 core-js 版本
                "corejs": 3
            }
        ]
    ],
    "plugins": [
		[
			"@babel/plugin-transform-runtime",
			{
				"absoluteRuntime": false,
				"corejs": 3,
				"helpers": true,
				"regenerator": true,
				"useESModules": false
			}
		]
	]
}

常用插件

生成 html 文件

安裝 html-webpack-plugin

yarn add html-webpack-plugin
  • html-webpack-plugin 默認(rèn)會(huì)創(chuàng)建一個(gè)沒有任何結(jié)構(gòu)樣式的 html 文件,會(huì)自動(dòng)引入打包輸出的所有資源。
    但是我們需要有結(jié)構(gòu)的 html 文件,所以需要再配置 options。
// 引入插件
const HtmlWebpackPlugin = require('html-webpack-plugin');

// 不傳參數(shù),默認(rèn)生成一個(gè) index.html 文件,并且將打包后輸出的所有資源插入 index.html 中
module.exports = {
	plugins: [
		new HtmlWebpackPlugin()
	]
};
// 傳參數(shù)
const path = require('path');

module.exports = {
	plugins: [
		new HtmlWebpackPlugin({
			 // 指定要生成的 html 模板文件,生成的 index.html 內(nèi)容跟 /src/index.html 相同,并且會(huì)自動(dòng)引入打包后輸出的所有資源
			template: path.resovle(__dirname, 'src/index.html'),
			filename: 'other.html' // 指定生成的 html 文件名
		})
	]
};

提取 css 為單獨(dú)文件

安裝 mini-css-extract-plugin

yarn add mini-css-extract-plugin
  • 使用 mini-css-extract-plugin 可以將打包后的 css 文件以 link 的方式插入 html
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

module.exports = {
	module: {
		rules: [
			{
				test: /\.css$/,
				use: [
					// 將 style-loader 換成 MiniCssExtractPlugin 內(nèi)置的loader
					// 從而將提取出的 css 文件以 link 的方式插入 html 中
					MiniCssExtractPlugin.loader,
					'css-loader',
					'postcss-loader'
				]
			}
		]
	},
	plugins: [
		// 默認(rèn)輸出到 output 指定目錄下,和 js 平級(jí),main.css
		new MiniCssExtractPlugin({
			// 可以通過參數(shù)指定打包后的路徑和文件名,輸出為 output 指定目錄下的 /css/style.css
			filename: 'css/style.css',
			// chunkFilename: 'css/[name].chunk.css' // css chunk 文件命名
		})
	]
};

Webpack5 基本使用 - 2,前端,webpack,軟件構(gòu)建

壓縮 js

  • mode: 'production' 自動(dòng)壓縮 js
  • mode: 'development' 設(shè)置 minimize: true 可壓縮
module.exports = {
	mode: 'production',
};
module.exports = {
	mode: 'development',
	optimization: {
		minimize: true
    }
};
  • 如果使用了 css-minimizer-webpack-plugin 壓縮 css,那么 js 壓縮會(huì)失效,需要手動(dòng)安裝 terser-webpack-plugin 插件
yarn add terser-webpack-plugin
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CssMinimizerWebpackPlugin = require("css-minimizer-webpack-plugin");
const TerserWebpackPlugin = require("terser-webpack-plugin");

module.exports = {
	mode: 'development',
	module: {
		rules: [
			{
				test: /\.css$/,
				use: [
					MiniCssExtractPlugin.loader,
					'css-loader',
					'postcss-loader'
				]
			}
		]
	},
	optimization: {
		minimize: true,
        minimizer: [
        	// 壓縮 js:解決壓縮 css 導(dǎo)致壓縮 js 失效的問題
            new TerserWebpackPlugin(),
            // 壓縮 css
            new CssMinimizerWebpackPlugin(),
        ],
    },
	plugins: [
		new MiniCssExtractPlugin({
			filename: 'css/style.css'
		})
	]
};

壓縮 css

安裝 css-minimizer-webpack-plugin

yarn add css-minimizer-webpack-plugin
  • css-minimizer-webpack-plugin 必須要配合 mini-css-extract-plugin 使用,只能對(duì)單獨(dú)的 css 文件進(jìn)行壓縮;
  • 只在 mode: 'production‘ 有效;
  • 如果希望在 mode: 'developmemt‘ 有效,需要設(shè)置 minimize: true
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CssMinimizerWebpackPlugin = require("css-minimizer-webpack-plugin");

module.exports = {
	mode: 'production',
	module: {
		rules: [
			{
				test: /\.css$/,
				use: [
					MiniCssExtractPlugin.loader,
					'css-loader',
					'postcss-loader'
				]
			}
		]
	},
	optimization: {
        minimizer: [
            // 壓縮 css
            new CssMinimizerWebpackPlugin(),
        ],
    },
	plugins: [
		new MiniCssExtractPlugin({
			filename: 'css/style.css'
		})
	]
};
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CssMinimizerWebpackPlugin = require("css-minimizer-webpack-plugin");

module.exports = {
	mode: 'development',
	module: {
		rules: [
			{
				test: /\.css$/,
				use: [
					MiniCssExtractPlugin.loader,
					'css-loader',
					'postcss-loader'
				]
			}
		]
	},
	optimization: {
		minimize: true,
        minimizer: [
            // 壓縮 css
            new CssMinimizerWebpackPlugin(),
        ],
    },
	plugins: [
		new MiniCssExtractPlugin({
			filename: 'css/style.css'
		})
	]
};

壓縮 html 文件

html-webpack-plugin
module.exports = {
	plugins: [
		new HtmlWebpackPlugin({
			 // 配置 minify 屬性進(jìn)行壓縮
			minify: {
				collapseWhitespace: true, // 移除空行
				removeComments: true // 移除注釋
			}
		})
	]
};
html-minimizer-webpack-plugin
const HtmlMinimizerWebpackPlugin = require("html-minimizer-webpack-plugin");

module.exports = {
	mode: 'production',
	plugins: [
		// 壓縮 html
        new HtmlMinimizerWebpackPlugin()
	]
};
const HtmlMinimizerWebpackPlugin = require("html-minimizer-webpack-plugin");

module.exports = {
	mode: 'development',
	optimization: {
		minimize: true
    },
	plugins: [
		// 壓縮 html
        new HtmlMinimizerWebpackPlugin()
	]
};

eslint 語法檢查

安裝 eslint、eslint-webpack-plugin

yarn add eslint eslint-webpack-plugin -D
const EslintPlugin = require("eslint-webpack-plugin");

module.exports = {
	plugins: [
		new EslintPlugin({
            context: path.resolve(__dirname, 'src'), // 需要檢測的根目錄
            exclude: 'node_modules', // 需要排除的目錄
            extensions: ['js'], // 需要檢查的文件類型
            fix: true // 自動(dòng)修復(fù)
        })
	]
};

eslint 規(guī)則配置 參考 https://eslint.cn/docs/rules/

// .eslintrc.js
module.exports = {
    root: true,
    env: {
        browser: true,
        node: true
    },
    extends: ['eslint:recommended'],
    rules: {
        'no-console': ['warn', { allow: ['warn', 'error'] }],
        'block-spacing': [2, 'always'],
        'brace-style': [2, '1tbs', { allowSingleLine: true }],
        'jsx-quotes': [2, 'prefer-single'],
        quotes: [
            2,
            'single',
            {
                avoidEscape: true,
                allowTemplateLiterals: true
            }
        ],
        'semi-spacing': [
            2,
            {
                before: false,
                after: true
            }
        ],
        'space-in-parens': [2, 'never'],
        'space-infix-ops': 'error',
        'space-unary-ops': 'error',
        indent: 0,
        semi: 'error',
        'comma-spacing': 0,
        'space-before-blocks': 0,
        'keyword-spacing': 0,
        'key-spacing': ['error', { afterColon: true }],
        'no-multiple-empty-lines': 0,
        'spaced-comment': [
            'error',
            'always',
            {
                line: {
                    markers: ['/'],
                    exceptions: ['-', '+']
                },
                block: {
                    markers: ['!'],
                    exceptions: ['*'],
                    balanced: true
                }
            }
        ],
        'space-before-function-paren': 0,
        'arrow-spacing': 'error',
        'object-curly-spacing': 0,
        'one-var-declaration-per-line': ['error', 'always'],
        'array-bracket-newline': ['error', 'consistent'],
        'no-lonely-if': 'error',
        'object-curly-newline': [
            'error',
            {
                ObjectPattern: { multiline: true },
                ImportDeclaration: { multiline: true },
                ExportDeclaration: { multiline: true }
            }
        ],
        'object-property-newline': ['error', { allowAllPropertiesOnSameLine: false }],
        'padding-line-between-statements': [
            'error',
            {
                blankLine: 'always',
                prev: ['const', 'let', 'var'],
                next: '*'
            },
            {
                blankLine: 'any',
                prev: ['const', 'let', 'var'],
                next: ['const', 'let', 'var']
            }
        ],
        'semi-style': ['error', 'last'],
        'switch-colon-spacing': 'error',
        'wrap-regex': 'error',
        'default-case': 'error',
        'guard-for-in': 'error',
        'no-else-return': 'error',
        'no-empty-function': 'error',
        'no-new-func': 'error',
        'no-useless-return': 'error',
        'symbol-description': 'error',
        'array-element-newline': ['error', 'consistent', { multiline: true }],
        'no-var': 'error',
        'one-var': ['error', 'consecutive'],
        'no-case-declarations': 0
    }
};
// .eslintignore
// 需要忽略 eslint 檢查的文件

/.idea/*
/node_modules/*
/.eslintrc.js
static/fonts/*
/yarn.lock
/yarn-error.log
/.gitignore

airbnb 規(guī)則

使用 airbnb 規(guī)則:如果不想自己一個(gè)個(gè)配置 eslint rules, 推薦使用 airbnb 規(guī)則,需要用 eslint-config-airbnb-base 庫。

yarn add eslint eslint-config-airbnb-base eslint-plugin-import -D
// 還需要在 package.json 中配置
{
	"eslintConfig": {
		"extends": "airbnb-base"
	}
}
@babel/eslint-parser

使用 @babel/eslint-parser 可以幫助你在使用 Babel 轉(zhuǎn)換代碼時(shí),避免 ESLint 中的語法錯(cuò)誤。同時(shí),它也可以在您的代碼中使用一些 Babel 特有的語法(如 jsxdecorators)時(shí),幫助 ESLint 正確解析和檢查代碼。

安裝 eslint@babel/core、@babe:/eslint-parser

yarn add eslint @babel/eslint-parser -D
yarn add @babel/core --save
module.exports = {
    root: true,
    env: {
        browser: true,
        node: true
    },
    extends: ['eslint:recommended'],
    parserOptions: {
        parser: '@babel/eslint-parser',
        sourceType: 'module',
        ecmaVersion: 2021,
        ecmaFeatures: {
            jsx: true,
            experimentalObjectRestSpread: true
        }
    },
    rules: {
    	// ...
    },
};
eslint-import

使用 import 報(bào)錯(cuò),需要安裝 eslint-plugin-import

yarn add eslint-plugin-import -D
module.exports = {
    root: true,
    env: {
        browser: true,
        node: true
    },
    globals: {},
    extends: ['eslint:recommended'],
    plugins: ['import'], // 在這里配置 import
};
stylelint

檢查樣式規(guī)范。

安裝 stylelint、stylelint-webpack-plugin

yarn add stylelint stylelint-webpack-plugin -D

安裝 stylelint-config-standard、 stylelint-order、 stylelint-config-css-modules

yarn add stylelint-config-standard stylelint-order stylelint-config-css-modules -D
  • stylelint-config-standardstylelint的推薦配置;
  • stylelint-order是用來在格式化css文件時(shí)對(duì)代碼的屬性進(jìn)行排序;
  • stylelint-config-css-modulescss-module的方案來處理樣式文件
const StylelintPlugin = require('stylelint-webpack-plugin');

module.exports = {
	mode: 'development',
	plugins: [
        new StylelintPlugin({
            configFile: path.resolve(__dirname, '.stylelintrc.js'), // 指定配置文件的位置
            fix: true,
            formatter: results => {
                // 在這里編寫自定義的格式化邏輯,將 Stylelint 檢查結(jié)果轉(zhuǎn)換為字符串
                // 返回格式化后的字符串
                return results
                    .map(result => {
                        const messages = result.warnings
                            .map(warning => {
                                return `  Line ${warning.line}, Column ${warning.column}: ${warning.text}`;
                            })
                            .join('\n');

                        return `File: ${result.source}\n${messages}`;
                    })
                    .join('\n');
            },
            context: path.resolve(__dirname, 'src'), // 需要檢測的目錄
            exclude: 'node_modules', // 需要排除的目錄
            extensions: ['css', 'scss', 'sass', 'less'], // 需要檢查的文件類型
            files: ['**/*.css', '**/*.scss'],
            failOnError: false,
            quiet: true,
            cache: true, // 開啟 stylelint 緩存
            cacheLocation: path.resolve(__dirname, '../node_modules/.cache/stylelintcache') // 指定緩存的位置
            // threads // 開啟多進(jìn)程和設(shè)置進(jìn)程數(shù)量
        })
    ],
};
// .stylelintrc.js
module.exports = {
	processors: [],
    plugins: ['stylelint-order'],
    extends: ['stylelint-config-standard', 'stylelint-config-css-modules'],
    rules: {
    	'color-no-invalid-hex': true,
        'selector-class-pattern': [
            // 命名規(guī)范 -
            '^([a-z][a-z0-9]*)(-[a-z0-9]+)*$',
            {
                message: 'Expected class selector to be kebab-case'
            }
        ],
        'string-quotes': 'single', // 單引號(hào)
        'at-rule-empty-line-before': null,
        'at-rule-no-unknown': null,
        'at-rule-name-case': 'lower', // 指定 @ 規(guī)則名的大小寫
        'length-zero-no-unit': true, // 禁止零長度的單位(可自動(dòng)修復(fù))
        'shorthand-property-no-redundant-values': true, // 簡寫屬性
        'number-leading-zero': 'never', // 小數(shù)不帶 0
        'declaration-block-no-duplicate-properties': true, // 禁止聲明快重復(fù)屬性
        'no-descending-specificity': true, // 禁止在具有較高優(yōu)先級(jí)的選擇器后出現(xiàn)被其覆蓋的較低優(yōu)先級(jí)的選擇器。
        'selector-max-id': 0, // 限制一個(gè)選擇器中 ID 選擇器的數(shù)量
        'max-nesting-depth': 3,
        indentation: [
            2,
            {
                // 指定縮進(jìn)  warning 提醒
                severity: 'warning'
            }
        ],
        'order/properties-order': [
            // 規(guī)則順序
            'position',
            'top',
            'right',
            'bottom',
            'left',
            'z-index',
            'display',
            'float',
            'width',
            'height',
            'max-width',
            'max-height',
            'min-width',
            'min-height',
            'padding',
            'padding-top',
            'padding-right',
            'padding-bottom',
            'padding-left',
            'margin',
            'margin-top',
            'margin-right',
            'margin-bottom',
            'margin-left',
            'margin-collapse',
            'margin-top-collapse',
            'margin-right-collapse',
            'margin-bottom-collapse',
            'margin-left-collapse',
            'overflow',
            'overflow-x',
            'overflow-y',
            'clip',
            'clear',
            'font',
            'font-family',
            'font-size',
            'font-smoothing',
            'osx-font-smoothing',
            'font-style',
            'font-weight',
            'line-height',
            'letter-spacing',
            'word-spacing',
            'color',
            'text-align',
            'text-decoration',
            'text-indent',
            'text-overflow',
            'text-rendering',
            'text-size-adjust',
            'text-shadow',
            'text-transform',
            'word-break',
            'word-wrap',
            'white-space',
            'vertical-align',
            'list-style',
            'list-style-type',
            'list-style-position',
            'list-style-image',
            'pointer-events',
            'cursor',
            'background',
            'background-color',
            'border',
            'border-radius',
            'content',
            'outline',
            'outline-offset',
            'opacity',
            'filter',
            'visibility',
            'size',
            'transform'
        ]
    }
};

其他插件

copy-webpack-plugin
yarn add copy-webpack-plugin
  • 拷貝文件:而是用來復(fù)制源代碼中已經(jīng)存在的文件(比如一些靜態(tài)資源),拷貝到指定的地方去;并不是用來復(fù)制打包生成的文件。
  • 比如有一些全局的配置,直接拷貝到目標(biāo)文件夾下去,后續(xù)這些全局配置文件內(nèi)容有改變,就不需要重新打包,可以直接替換部署的文件
const CopyPlugin = require("copy-webpack-plugin");

module.exports = {
  plugins: [
    new CopyPlugin({
      patterns: [
        { from: path.resolve(__dirname, "src", "static"), to: "public" }
      ]
    })
  ]
};

Webpack5 基本使用 - 2,前端,webpack,軟件構(gòu)建文章來源地址http://www.zghlxwxcb.cn/news/detail-820107.html

到了這里,關(guān)于Webpack5 基本使用 - 2的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場。本站僅提供信息存儲(chǔ)空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請(qǐng)注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請(qǐng)點(diǎn)擊違法舉報(bào)進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • 前端工程化第一章:webpack5基礎(chǔ)(上)

    前端工程化第一章:webpack5基礎(chǔ)(上)

    Webpack 是一個(gè)現(xiàn)代 JavaScript 應(yīng)用程序的靜態(tài)模塊 打包器 。它是一個(gè)用于 將代碼編譯成瀏覽器可識(shí)別的格式 的工具。 webpack 可以實(shí)現(xiàn)以下的功能: 代碼轉(zhuǎn)換 : TypeScript 編譯成 JavaScript 、 SCSS 、 less 編譯成 CSS 等。 文件優(yōu)化 :壓縮 JavaScript 、 CSS 、 HTML 代碼, 壓縮合并圖片

    2024年02月16日
    瀏覽(32)
  • 【快速搞定Webpack5】基本配置及開發(fā)模式介紹(二)

    【快速搞定Webpack5】基本配置及開發(fā)模式介紹(二)

    在開始使用 webpack 之前么,我們需要對(duì) Webpack 的配置有一定的認(rèn)識(shí)。 1. enty(入口) 指示 webpack 從哪個(gè)文件開始打包 2. output(輸出) 指示 webpack 打包完的文件輸出到哪里去,如何命名等 3. loader(加載器) webpack 本身只能處理 js、json 等資源,其他資源需要借助 loader 、 webp

    2024年02月21日
    瀏覽(18)
  • 基于vue3+webpack5+qiankun實(shí)現(xiàn)微前端

    基于vue3+webpack5+qiankun實(shí)現(xiàn)微前端

    一 主應(yīng)用改造(又稱基座改造) 1 在主應(yīng)用中安裝qiankun(npm i qiankun -S) ?2 在src下新建micro-app.js文件,用于存放所有子應(yīng)用。 ?3 改造vue.config.js,允許跨域訪問子應(yīng)用頁面 ?4 改造main.js ? 5 在App.vue中寫響應(yīng)跳轉(zhuǎn)子應(yīng)用(根據(jù)自己的項(xiàng)目找對(duì)應(yīng)位置寫,不局限于App.vue) ? 需要注

    2024年02月13日
    瀏覽(32)
  • Webpack5 基礎(chǔ)使用筆記

    [webpack中文文檔](概念 | webpack 中文文檔 | webpack中文文檔 | webpack中文網(wǎng) (webpackjs.com)): 本質(zhì)上, webpack 是一個(gè)用于現(xiàn)代 JavaScript 應(yīng)用程序的 靜態(tài)模塊打包工具 。當(dāng) webpack 處理應(yīng)用程序時(shí),它會(huì)在內(nèi)部從一個(gè)或多個(gè)入口點(diǎn)構(gòu)建一個(gè) 依賴圖(dependency graph),然后將你項(xiàng)目中所需的

    2024年02月08日
    瀏覽(53)
  • 使用webpack5+TypeScript+npm發(fā)布組件庫

    使用webpack5+TypeScript+npm發(fā)布組件庫

    ? ? ? ? 作為一只前端攻城獅,沒有一個(gè)屬于自己的組件庫,那豈不是獅子沒有了牙齒,士兵沒有了武器,姑娘沒有了大寶SOD蜜,你沒有了我.... ? ? ? ? 言歸正傳,下面將給大家介紹如何通過webpack5編譯一個(gè)TS組件發(fā)布到NPM平臺(tái)。 ? ? ? ? 1、通過webpack5初始化一個(gè)typescript環(huán)

    2024年04月16日
    瀏覽(19)
  • webpack4和webpack5有什么區(qū)別

    webpack4和webpack5有什么區(qū)別

    Webpack4和Webpack5是兩個(gè)版本的Webpack,其中Webpack5是Webpack的最新版本。 性能:Webpack5相對(duì)于Webpack4有更好的性能表現(xiàn),尤其是在構(gòu)建速度和Tree Shaking方面。 模塊聯(lián)邦:Webpack5引入了模塊聯(lián)邦的概念,可以讓多個(gè)Webpack構(gòu)建的應(yīng)用程序共享模塊,從而減少了代碼冗余。 持久性緩存:

    2024年02月01日
    瀏覽(21)
  • webpack5性能優(yōu)化

    webpack5性能優(yōu)化

    ?注意:開啟緩存,配置后打包是就能緩存babel webpack.common.js文件命中緩存cacheDirectory ????????Directory/d??rekt?ri/目錄; ? 測試:? 打包后的結(jié)果:? 注意:打包后promise的打包文件會(huì)變化文件名 ?? 注意:引入第三方模塊,模塊可能有許多東西是我們不需要的,而引入時(shí)會(huì)默認(rèn)

    2024年02月16日
    瀏覽(22)
  • webpack5高級(jí)配置

    webpack5高級(jí)配置

    注意:webpack5基本配置只是打包產(chǎn)出一個(gè)html文件?,想要產(chǎn)出多個(gè)html就需要進(jìn)行過入口的配置 webpack.common.js 注意:公共文件中的入口需要引入兩個(gè)js文件 ?webpack.prod.js 注意:輸出的時(shí)候利用[name]根據(jù)輸入的文件名來確定導(dǎo)出的文件名稱! webpack.common.js 注意:針對(duì)多個(gè)html文件

    2024年02月15日
    瀏覽(43)
  • webpack5 學(xué)習(xí)之路

    1.視頻 01-課程介紹_嗶哩嗶哩_bilibili 2.配套資料 依賴環(huán)境 | 尚硅谷 Web 前端之 Webpack5 教程 3.webpack 官方文檔 入口起點(diǎn)(entry points) | webpack 中文文檔 4.vue cli 官方文檔 介紹 | Vue CLI 挖礦:Coding Tree

    2024年02月15日
    瀏覽(20)
  • webpack5(一)

    webpack5(一)

    webpack是一個(gè)靜態(tài)資源打包工具,它會(huì)以一個(gè)或者多個(gè)文件作為打包的入口,將整個(gè)項(xiàng)目的所有文件編譯組合成一個(gè)或多個(gè)文件輸出出去。輸出的文件就是編譯好的文件,可以在瀏覽器端運(yùn)行。一般將 webpack 輸出的文件稱為 bandle 。 webpack 本身的功能也是有限的,一共有兩種模

    2024年02月11日
    瀏覽(22)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請(qǐng)作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包