hooyantsing's Blog

P22 oneOf

字数统计: 408阅读时长: 2 min
2020/12/01

尚硅谷2020最新版Webpack5实战教程

什么是oneOf

优化匹配loader,loader 只会匹配一个,避免多个loader多次匹配,提升速度。

注意:不能有两个配置处理同一个类型文件,第二个loader将失效。

如何使用

编写配置文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
const { resolve } = require("path");
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');

process.env.NODE_ENV = 'production';

const commonCssLoader = [
MiniCssExtractPlugin.loader,
'css-loader',
'postcss-loader'
];

module.exports = {
entry: './src/js/index.js',
output: {
filename: 'js/built.js',
path: resolve(__dirname, 'build'),
publicPath:'./'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
enforce: 'pre',
loader: 'eslint-loader',
options: {
fix: true
}
},
{
/*
[优化]oneOf
以下 loader 只会匹配一个,避免多个loader多次匹配
注意:不能有两个配置处理同一个类型文件
*/
oneOf: [
{
test: /\.css$/,
use: [...commonCssLoader]
},
{
test: /\.less$/,
use: [...commonCssLoader, 'less-loader']
},
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
options: {
presets: [
[
'@babel/preset-env',
{
useBuiltIns: 'entry',
corejs: {
version: 3
},
targets: {
chrome: '60',
firefox: "60",
ie: '9',
safari: '10',
edge: '17'
}
}
]
],
"plugins": ["@babel/plugin-transform-runtime"]
}
},
{
test: /\.(jpg|png|gif)/,
loader: 'url-loader',
options: {
limit: 8 * 1024,
name: '[hash:10].[ext]',
outputPath: 'imgs',
esModule: false
}
},
{
test: /\.html$/,
loader: 'html-loader'
},
{
exclude: /\.(js|css|less|html|jpg|png|gif)/,
loader: 'file-loader',
options: {
outputPath: 'media'
}
}
]
}
]
},
plugins: [
new MiniCssExtractPlugin({
filename: 'css/built.css'
}),
new OptimizeCssAssetsWebpackPlugin(),
new HtmlWebpackPlugin({
template: './src/index.html',
minify: {
collapseWhitespace: true,
removeComments: true
}
})
],
mode: 'production',
devServer: {
contentBase: resolve(__dirname,'build'),
compress: true,
port: 3000
}
};
CATALOG
  1. 1. 什么是oneOf
  2. 2. 如何使用