Webpack5 基本使用 - 2

这篇具有很好参考价值的文章主要介绍了Webpack5 基本使用 - 2。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

常用 loader

  • loader 是辅助打包工具。
  • webpack 默认只能打包 js 文件,打包其它模块就需要配置 loader 来告诉 webpack 该怎么去打包其它文件。
  • loader 可以将文件从不同的语言转换为 JavaScript
  • 一类文件如果需要多个 loader 处理,loader 的执行顺序是从后往前。

打包样式文件

打包 css

css 文件需要先用 css-loader 处理,再用 style-loader 插入 <style></style>标签中。

安装 css-loader、style-loader

yarn add css-loader style-loader --save
module.exports = {
	module: {
		rules: [
			{
				test: /\.css$/,
				use: [
					// 再用 style-loader 创建 style 标签插入 <head></head> 标签中
					'style-loader',
					// css 文件需要先用 css-loader 处理,将 css 编译成 commonjs 整合到 js 中
					'css-loader'
				]
			}
		]
	}
};
// 使用 localIdentName 自定义生成的样式名称格式,可选的参数有: 
// [path] 表示样式表相对于项目根目录所在路径 
// [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,软件构建

样式兼容性处理

postcss-loader 自动添加浏览器前缀。

使用 autofixer 插件辅助

autoprefixer 可以指定需要兼容的浏览器。

安装 postcss-loader、autofixer

yarn add postcss-loader autoprefixer --save
// 通过配置加载指定的 css 兼容性样式
// postcss-loader 在 css-loader 之前调用
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": [
													// 兼容最近的一个 chrome 的版本
													"last 1 chrome version",
													"last 1 firefox version",
													"last 1 safari version",
												],
												"production": [
													// 大于 99.8% 的浏览器
													">0.2%",
													// 不要已经死了的浏览器:比如 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 需要同时安装 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 需要同时安装 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'
				]
			}
		]
	}
};

打包图片、字体等静态资源

打包图片

webpack4 需要使用url-loaderfile-loaderwebpack5 已内置,使用模块 asset

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

Webpack5 基本使用 - 2,前端,webpack,软件构建

Webpack5 基本使用 - 2,前端,webpack,软件构建

const path = require('path');

module.exports = {
  output: {
    // ...
    // 指定所有 assetModule 文件的输出目录,同时重命名输出的文件名称
   	// 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,软件构建

asset/inline
  • url-loaderwebpack5 中已被 asset/inline 替换。
  • 打包输出的数据 URI 使用 Base64 算法编码的文件内容(可以减少 http 请求数量,但是体积会变大)
module.exports = {
	module: {
		rules: [
			{
				test: /\.(png|jpg|jpeg|gif|PNG)$/,
				type: 'asset/inline'
			}
		]
	}
};
asset
module.exports = {
	module: {
		output: {
			// ...
			// 指定 assetModule 文件的输出目录,同时重命名输出的文件名称
        	// assetModuleFilename: 'images/[hash:8][ext][query]'
		},
		rules: [
			{
				test: /\.(png|jpeg|gif|PNG)$/,
				type: 'asset',
				parser: {
					// 自定义转 base64 的界限
					dataUrlCondition: {
						// 小于 10kb 的图片转 base64
						maxSize: 10 * 1024 // 10kb
					}
				},
				generator: {
					// 跟 assetModuleFilename 之中选一个即可
					// 输出图片的名称
					filename: 'images/[hash:8][ext][query]'
				}
			}
		]
	}
};
打包字体图标资源
module.exports = {
	module: {
		output: {
			// ...
			// 指定图片文件的输出目录,同时重命名输出的文件名称
        	// assetModuleFilename: 'fonts/[hash:8][ext][query]'
		},
		rules: [
			{
				test: /\.(ttf|otf|woff2?)$/,
				type: 'asset',
				generator: {
					// 跟 assetModuleFilename 之中选一个即可
					// 输出文件的名称
					filename: 'fonts/[hash:8][ext][query]'
				}
			}
		]
	}
};
打包其他资源
module.exports = {
	module: {
		output: {
			// ...
			// 指定图片文件的输出目录,同时重命名输出的文件名称
        	// assetModuleFilename: 'media/[hash:8][ext][query]'
		},
		rules: [
			{
				test: /\.(mp3|mp4|avi|excel)$/,
				type: 'asset',
				generator: {
					// 跟 assetModuleFilename 之中选一个即可
					// 输出文件的名称
					filename: 'media/[hash:8][ext][query]'
				}
			}
		]
	}
};

js 兼容性处理

因为不是所有浏览器都能识别 es6 语法,所以需要通过 babel 进行转换,将 es6 语法转换成所有浏览器都可以识别的 es5 语法。

使用最新版本 babel

最新版本 babel 已支持转换 generator 函数,以及最新的 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": []
}
转换 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
转换基本语法

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

module.exports = {
	module: {
		rules: [
			{
				test: /\.js$/,
				loader: 'babel-loader',
				exclude: /mode_modules/,
				// 第一种配置,在这里通过 options 配置预设
				options: {
					// 预设:指示babel做什么样的兼容性处理
					presets: '@babel/preset-env'
				}
			}
		]
	}
};
// 第二种配置:新建 .babelrc 文件
{
    "presets": ["@babel/preset-env"],
    "plugins": []
}
  • @babel/preset-env 不能转换所有的 es6 语法(比如 async awaitgenerator 函数),只能转换基本语法;
  • 最新版本的已支持,如要测试请使用低版本 babel
@babel/pollyfill
  • @babel/pollyfill 相当于 babel 的补丁,使用 @babel/pollyfill 可以转换所有语法。

  • @babel/pollyfillcore-jsregenerator 的集合(推荐单独安装 core-jsregenerator ,因为@babel/pollyfill 会污染全局变量)

  • @babel/pollyfillbabel 7.4.0 以后已被弃用,如果想测试,需要安装低版本 babel 测试。

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

  • 会将所有的兼容性代码全部引入,体积太大,而且会污染全局变量

// 在需要处理的文件中通过 import 引入
import '@babel/pollyfill';
按需加载
  • 使用 core-js 可以解决 @babel/pollyfill 全部引入,导致体积太大的问题。
  • core-js@babel/pollyfill 不能同时使用,只安装一个即可, @babel/pollyfill 内置有 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 默认会创建一个没有任何结构样式的 html 文件,会自动引入打包输出的所有资源。
    但是我们需要有结构的 html 文件,所以需要再配置 options
// 引入插件
const HtmlWebpackPlugin = require('html-webpack-plugin');

// 不传参数,默认生成一个 index.html 文件,并且将打包后输出的所有资源插入 index.html 中
module.exports = {
	plugins: [
		new HtmlWebpackPlugin()
	]
};
// 传参数
const path = require('path');

module.exports = {
	plugins: [
		new HtmlWebpackPlugin({
			 // 指定要生成的 html 模板文件,生成的 index.html 内容跟 /src/index.html 相同,并且会自动引入打包后输出的所有资源
			template: path.resovle(__dirname, 'src/index.html'),
			filename: 'other.html' // 指定生成的 html 文件名
		})
	]
};

提取 css 为单独文件

安装 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 内置的loader
					// 从而将提取出的 css 文件以 link 的方式插入 html 中
					MiniCssExtractPlugin.loader,
					'css-loader',
					'postcss-loader'
				]
			}
		]
	},
	plugins: [
		// 默认输出到 output 指定目录下,和 js 平级,main.css
		new MiniCssExtractPlugin({
			// 可以通过参数指定打包后的路径和文件名,输出为 output 指定目录下的 /css/style.css
			filename: 'css/style.css',
			// chunkFilename: 'css/[name].chunk.css' // css chunk 文件命名
		})
	]
};

Webpack5 基本使用 - 2,前端,webpack,软件构建

压缩 js

  • mode: 'production' 自动压缩 js
  • mode: 'development' 设置 minimize: true 可压缩
module.exports = {
	mode: 'production',
};
module.exports = {
	mode: 'development',
	optimization: {
		minimize: true
    }
};
  • 如果使用了 css-minimizer-webpack-plugin 压缩 css,那么 js 压缩会失效,需要手动安装 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 导致压缩 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 使用,只能对单独的 css 文件进行压缩;
  • 只在 mode: 'production‘ 有效;
  • 如果希望在 mode: 'developmemt‘ 有效,需要设置 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 属性进行压缩
			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 // 自动修复
        })
	]
};

eslint 规则配置 参考 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 规则

使用 airbnb 规则:如果不想自己一个个配置 eslint rules, 推荐使用 airbnb 规则,需要用 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 转换代码时,避免 ESLint 中的语法错误。同时,它也可以在您的代码中使用一些 Babel 特有的语法(如 jsxdecorators)时,帮助 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 报错,需要安装 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

检查样式规范。

安装 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文件时对代码的属性进行排序;
  • 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 检查结果转换为字符串
                // 返回格式化后的字符串
                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 // 开启多进程和设置进程数量
        })
    ],
};
// .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': [
            // 命名规范 -
            '^([a-z][a-z0-9]*)(-[a-z0-9]+)*$',
            {
                message: 'Expected class selector to be kebab-case'
            }
        ],
        'string-quotes': 'single', // 单引号
        'at-rule-empty-line-before': null,
        'at-rule-no-unknown': null,
        'at-rule-name-case': 'lower', // 指定 @ 规则名的大小写
        'length-zero-no-unit': true, // 禁止零长度的单位(可自动修复)
        'shorthand-property-no-redundant-values': true, // 简写属性
        'number-leading-zero': 'never', // 小数不带 0
        'declaration-block-no-duplicate-properties': true, // 禁止声明快重复属性
        'no-descending-specificity': true, // 禁止在具有较高优先级的选择器后出现被其覆盖的较低优先级的选择器。
        'selector-max-id': 0, // 限制一个选择器中 ID 选择器的数量
        'max-nesting-depth': 3,
        indentation: [
            2,
            {
                // 指定缩进  warning 提醒
                severity: 'warning'
            }
        ],
        'order/properties-order': [
            // 规则顺序
            '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
  • 拷贝文件:而是用来复制源代码中已经存在的文件(比如一些静态资源),拷贝到指定的地方去;并不是用来复制打包生成的文件。
  • 比如有一些全局的配置,直接拷贝到目标文件夹下去,后续这些全局配置文件内容有改变,就不需要重新打包,可以直接替换部署的文件
const CopyPlugin = require("copy-webpack-plugin");

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

Webpack5 基本使用 - 2,前端,webpack,软件构建文章来源地址https://www.toymoban.com/news/detail-820107.html

到了这里,关于Webpack5 基本使用 - 2的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 前端工程化第一章:webpack5基础(上)

    Webpack 是一个现代 JavaScript 应用程序的静态模块 打包器 。它是一个用于 将代码编译成浏览器可识别的格式 的工具。 webpack 可以实现以下的功能: 代码转换 : TypeScript 编译成 JavaScript 、 SCSS 、 less 编译成 CSS 等。 文件优化 :压缩 JavaScript 、 CSS 、 HTML 代码, 压缩合并图片

    2024年02月16日
    浏览(33)
  • 【快速搞定Webpack5】基本配置及开发模式介绍(二)

    在开始使用 webpack 之前么,我们需要对 Webpack 的配置有一定的认识。 1. enty(入口) 指示 webpack 从哪个文件开始打包 2. output(输出) 指示 webpack 打包完的文件输出到哪里去,如何命名等 3. loader(加载器) webpack 本身只能处理 js、json 等资源,其他资源需要借助 loader 、 webp

    2024年02月21日
    浏览(31)
  • 基于vue3+webpack5+qiankun实现微前端

    一 主应用改造(又称基座改造) 1 在主应用中安装qiankun(npm i qiankun -S)  2 在src下新建micro-app.js文件,用于存放所有子应用。  3 改造vue.config.js,允许跨域访问子应用页面  4 改造main.js   5 在App.vue中写响应跳转子应用(根据自己的项目找对应位置写,不局限于App.vue)   需要注

    2024年02月13日
    浏览(46)
  • Webpack5 基础使用笔记

    [webpack中文文档](概念 | webpack 中文文档 | webpack中文文档 | webpack中文网 (webpackjs.com)): 本质上, webpack 是一个用于现代 JavaScript 应用程序的 静态模块打包工具 。当 webpack 处理应用程序时,它会在内部从一个或多个入口点构建一个 依赖图(dependency graph),然后将你项目中所需的

    2024年02月08日
    浏览(27)
  • 使用webpack5+TypeScript+npm发布组件库

            作为一只前端攻城狮,没有一个属于自己的组件库,那岂不是狮子没有了牙齿,士兵没有了武器,姑娘没有了大宝SOD蜜,你没有了我....         言归正传,下面将给大家介绍如何通过webpack5编译一个TS组件发布到NPM平台。         1、通过webpack5初始化一个typescript环

    2024年04月16日
    浏览(31)
  • webpack4和webpack5有什么区别

    Webpack4和Webpack5是两个版本的Webpack,其中Webpack5是Webpack的最新版本。 性能:Webpack5相对于Webpack4有更好的性能表现,尤其是在构建速度和Tree Shaking方面。 模块联邦:Webpack5引入了模块联邦的概念,可以让多个Webpack构建的应用程序共享模块,从而减少了代码冗余。 持久性缓存:

    2024年02月01日
    浏览(25)
  • webpack5 (二)

    是 js 编译器,主要的作用是将 ES6 语法编写的代码转换为向后兼容的 js 语法,以便可以运行在当前版本和旧版本的浏览器或其他环境中。 它的配置文件有多种写法: babel.config.*(js/json) babelrc.*(js/json) package.json 中的 babel:不需要创建文件,在原有的文件基础上写。 babel 会查找

    2024年02月10日
    浏览(31)
  • Webpack5 SourceMap

    提示:以下是本篇文章正文内容,下面案例可供参考 为什么需要SourceMap 开发时我们运行的代码是经过 Webpack 编译压缩合并之后的,这样的目的是以提高应用程序的性能,但是这种优化也给调试问题带来了困难,因为压缩后的代码难以追踪和调试。这时候,SourceMap技术就能派

    2024年02月13日
    浏览(29)
  • webpack5(一)

    webpack是一个静态资源打包工具,它会以一个或者多个文件作为打包的入口,将整个项目的所有文件编译组合成一个或多个文件输出出去。输出的文件就是编译好的文件,可以在浏览器端运行。一般将 webpack 输出的文件称为 bandle 。 webpack 本身的功能也是有限的,一共有两种模

    2024年02月11日
    浏览(28)
  • webpack5性能优化

     注意:开启缓存,配置后打包是就能缓存babel webpack.common.js文件命中缓存cacheDirectory         Directory/dəˈrektəri/目录;   测试:  打包后的结果:  注意:打包后promise的打包文件会变化文件名    注意:引入第三方模块,模块可能有许多东西是我们不需要的,而引入时会默认

    2024年02月16日
    浏览(36)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包