请设计一个 Webpack 配置方案,该方案能够同时处理 Web 和移动端的资源,确保每个平台在生产构建中都有优化的资产管理和压缩设置。
为了同时处理 Web 和移动端资源,并确保生产构建中的优化资产管理和压缩设置,我们需要编写一个灵活且模块化的 Webpack 配置。这里将采用多配置对象的方式来定义 Web 和移动端的不同配置,同时使用webpack-merge库来共享通用配置,从而实现代码的最大复用和维护性。
首先,我们安装必要的依赖:
npm install --save-dev webpack webpack-merge html-webpack-plugin clean-webpack-plugin terser-webpack-plugin optimize-css-assets-webpack-plugin
然后定义一个基本配置文件webpack.base.js,包含所有平台共用的部分,如入口、输出路径、模块规则、插件等:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
module.exports = {
entry: './src/index.js',
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist'),
},
module: {
rules: [
{
test: /.js$/, // 解析JS文件
exclude: /node_modules/, // 排除node_modules中的文件
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env'], // 使用Babel转译ES6+语法
},
},
},
{
test: /.(png|jpe?g|gif|svg)$/, // 图片文件处理
use: ['file-loader'],
},
{
test: /.(scss|css)$/, // SCSS/LESS/CSS文件处理
use: [
'style-loader',
'css-loader',
'postcss-loader',
'sass-loader',
],
},
],
},
plugins: [
new CleanWebpackPlugin(), // 清理输出目录
new HtmlWebpackPlugin({
template: './src/index.html', // HTML模板路径
favicon: './src/favicon.ico', // Favicon路径
}),
],
optimization: {
splitChunks: {
cacheGroups: {
vendor: {
test: /[\/]node_modules[\/]/, // 匹配node_modules中的文件
name: 'vendors',
chunks: 'all',
},
},
},
},
};
接下来,创建webpack.web.js和webpack.mobile.js,用于定义Web和移动端的具体配置差异。这里主要调整输出路径、压缩设置、特定的插件等:
// webpack.web.js
const merge = require('webpack-merge');
const common = require('./webpack.base.js');
const TerserPlugin = require('terser-webpack-plugin');
module.exports = merge(common, {
output: {
publicPath: '/', // 生产环境下资源文件的公共路径
},
optimization: {
minimizer: [
new TerserPlugin({
terserOptions: {
compress: {
drop_console: true, // 移除console.*调用
},
},
}),
],
},
});
// webpack.mobile.js
const merge = require('webpack-merge');
const common = require('./webpack.base.js');
module.exports = merge(common, {
output: {
publicPath: '/mobile/', // 移动端生产环境下资源文件的公共路径
},
optimization: {
minimize: true,
},
module: {
rules: [
{
test: /.(png|jpe?g|gif|svg)$/, // 移动端图片处理优化
use: [
{
loader: 'file-loader',
options: {
outputPath: 'images/mobile',
name: '[name].[ext]',
},
},
],
},
],
},
});
以上配置解决了同时处理Web和移动端资源的问题,通过使用webpack-merge库来管理和扩展不同环境下的配置,既保证了代码的复用性,又方便了未来的维护。