多个 loader,但是每个文件只能匹配一个 loader,被一个 loader 处理,因此可以使用 oneOf 唯一匹配,不需要每个文件把所有的 loader 都询问一遍,可以提高 loader 的执行效率
webpack.config.js:
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‘ //复用loader const commonCssLoader = [ MiniCssExtractPlugin.loader, ‘css-loader‘, { loader:‘postcss-loader‘, options:{ ident:‘postcss‘, plugins:()=>[require(‘postcss-preset-env‘)()] } } ] module.exports={ entry:‘./src/index.js‘, output:{ filename:‘bundle.js‘, path:resolve(__dirname,‘build‘) }, module:{ rules:[ { test: /\.js$/, exclude: /node_modules/, enforce: ‘pre‘, //优先执行,正常的,一个文件只能被一个loader处理,当一个文件要被多个loader处理, //一定要指定loader执行的先后顺序,先执行eslint再执行babel loader: ‘eslint-loader‘, options: { fix: true } }, //以下loader中只会匹配一个,注意不能有两个loader处理同一种类型文件,所以eslint-loader放在oneOf匹配之前执行 { oneOf:[ { test: /\.css$/, use: [...commonCssLoader] }, { test: /\.less$/, use: [...commonCssLoader] }, { test: /\.js$/, exclude: /node_modules/, loader: ‘babel-loader‘, options: { presets: [ [‘@babel/preset-env‘, { useBuiltIns: ‘usage‘, corejs: { version: 3 }, targets: { chrome: ‘60‘, firefox: ‘50‘ } }] ] } }, { 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:‘bundle.css‘ }), new OptimizeCssAssetsWebpackPlugin(), new HtmlWebpackPlugin({ template:‘./src/index.html‘, minify:{ collapseWhitespace:true, removeComments:true } }) ], mode:‘production‘