接上期 webpack的基础配置
同样附上个人git仓库地址:https://gitee.com/zhaosir1/webpack-base-react-cli.git
详细注释请参考:webpack的基础配置 https://blog.csdn.net/qq_45142260/article/details/125345042
废话不多说,直接上代码
webpack.config.js
其中 imagemin-gifsicle imagemin-jpegtran imagemin-optipng imagemin-svgo 这几个插件不太容易能够下载下来,可私聊我单独发,或者访问我主页,我上传的资源,其中有个关于webpack图片压缩的插件下载即可。下载地址:https://download.csdn.net/download/qq_45142260/85709385
webpack.config.js文件是 把webpack.dev.js和webpack.prod.js合并之后的文件,这样会使文件比较整洁一点
const EslintWebpackPlugin = require('eslint-webpack-plugin')
const HtmlWebpackPlugin = require("html-webpack-plugin")
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const CssMinimizerWebpackPlugin = require('css-minimizer-webpack-plugin')
const TerserWebpackPlugin = require('terser-webpack-plugin')
const ImageMinimizerPlugin = require('image-minimizer-webpack-plugin')
const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin');
const CopyPlugin = require("copy-webpack-plugin");
const path = require('path')
// 判断当前环境
const isProduction = process.env.NODE_ENV === 'production'
function getStyleLoaders (pre) {
return [
//根据不同环境使用不同的loader--开发环境不需要css压缩和单独抽离
isProduction ? MiniCssExtractPlugin.loader : 'style-loader',
'css-loader',
{
// 处理css兼容性
// 配合package.json 中browserslit来指定兼容性
loader:'postcss-loader',
options:{
postcssOptions:{
plugins:['postcss-preset-env'],
}
}
},
pre && {
loader:pre,
// 针对antd的高级配置使用
options:pre === 'less-loader'?{
// antd的主题色设置
lessOptions: {
modifyVars: { '@primary-color': '#f00' },
javascriptEnabled: true,
}
}:{}
}
].filter(Boolean)
}
module.exports = {
entry: './src/main.js',
output: {
// 环境判断,输出文件位置、文件名称、缓存文件名称等
path: isProduction ? path.resolve(__dirname,'../dist') : undefined,
filename: isProduction ? 'static/js/[name].[contenthash:10].chunk.js' : 'static/js/[name].js',
chunkFilename: isProduction ? 'static/js/[name].[contenthash:10].chunk.js' : 'static/js/[name].chunk.js',
assetModuleFilename: 'static/media/[hash:10][ext][query]',
clean:true
},
module: {
rules: [
//css
{
test: /\.css$/,
use:getStyleLoaders(),
},
{
test: /\.less$/,
use:getStyleLoaders('less-loader'),
},
{
test: /\.s[ac]ss$/,
use:getStyleLoaders('sass-loader'),
},
{
test: /\.styl$/,
use:getStyleLoaders('stylus-loader'),
},
//图片
{
test:/\.(jpe?g|png|svg|gif)/,
type:"asset",
parser:{
dataUrlCondition:{
maxSize:10 * 1024,
},
}
},
//其他资源
{
test:/\.(woff2?|ttf)/,
type:'asset/resource'
},
//js
{
test:/\.jsx?$/,
include:path.resolve(__dirname,'../src'),
loader:'babel-loader',
options:{
cacheDirectory:true, //开启缓存
cacheCompression:false, //不压缩缓存文件
plugins:[
// 生产环境不需要激活HMR功能
!isProduction && 'react-refresh/babel' //激活js的HMR功能
].filter(Boolean)
}
}
]
},
// 处理html
plugins:[
// Eslint语法检查
new EslintWebpackPlugin({
context:path.resolve(__dirname,'../src'), //指定处理文件范围
exclude:'node_modules', //排除node_modules文件夹
cache:true, //开启缓存
//配置缓存文件位置
cacheLocation:path.resolve(__dirname,'../node_modules/.cache/.eslintcache'),
}),
// 处理html文件内容
new HtmlWebpackPlugin({
//配置处理 public 下的 index.html 文件
template:path.resolve(__dirname,'../public/index.html')
}),
//开发环境不需要css压缩
isProduction && new MiniCssExtractPlugin({
filename:'static/css/[name],[contenthash:10].css',
chunkFilename:'static/css/[name],[contenthash:10].chunk.css',
}),
//开发环境不需要public文件的copy
isProduction && new CopyPlugin({
patterns:[{from:path.resolve(__dirname,'../public'),to:path.resolve(__dirname,'../dist'),globOptions: {
dot: true,
gitignore: true,
ignore: ["**/index.html*"],//忽略index.html文件
},}]
}),
!isProduction && new ReactRefreshWebpackPlugin()
].filter(Boolean), //过滤掉为undefined的plugin
mode:isProduction?'production':'development',
devtool:isProduction ? 'source-map':'cheap-module-source-map',
optimization:{
splitChunks:{
chunks:'all',
// 由于node_modules文件打包之后会生成一个特别大的文件夹,
// 因此需要手动配置分包
cacheGroups:{
// react react-dom react-router-dom 相关的 一起打包
react:{
test:/[\\/]node_modules[\\/]react(.*)?[\\/]/,
name:'chunk-react',//文件名称
priority:40
},
// antd单独打包
antd:{
test:/[\\/]node_modules[\\/]antd[\\/]/,
name:'chunk-antd',//文件名称
priority:30
},
// 剩下的node_module单独打包
libs:{
test:/[\\/]node_modules[\\/]/,
name:'chunk-libs',
priority:20
}
}
},
runtimeChunk:{
name:entrypoint => `runtime~${entrypoint.name}.js`
},
//minimize 是否需要压缩
//开发环境不需要压缩,因此直接配置minimize:isProduction即可
//webpack会自动忽略 minimizer 的配置项
minimize:isProduction,
minimizer: [
new CssMinimizerWebpackPlugin(),
new TerserWebpackPlugin(),
new ImageMinimizerPlugin({
minimizer: {
implementation: ImageMinimizerPlugin.imageminGenerate,
options: {
plugins: [
["gifsicle", { interlaced: true }],
["jpegtran", { progressive: true }],
["optipng", { optimizationLevel: 5 }],
[
"svgo",
{
plugins: [
"preset-default",
"prefixIds",
{
name: "sortAttrs",
params: {
xmlnsOrder: "alphabetical",
},
},
],
},
],
],
},
},
}),
]
},
// webpack解析模块加载选项
resolve:{
// 自动补全文件扩展名
extensions:['.jsx','.js','.json']
},
devServer:{
host:'localhost',
port:3001,
open:true,
hot:true,
historyApiFallback:true, //解决前端路由刷新404问题
},
performance:false,//关闭性能分析,提升打包速度
}
import React,{Suspense,lazy} from "react";
// import Home from "./pages/Home";
// import About from "./pages/About";
import {Link,Routes,Route} from 'react-router-dom'
import {Button} from 'antd'
const Home = lazy(() => import(/* webpackChunkName: 'home' */'./pages/Home'))
const About = lazy(() => import(/* webpackChunkName: 'about' */'./pages/About'))
function App(){
return (
<>
<h1>App</h1>
<Button type="primary">按钮</Button>
<ul>
<li>
<Link to="/home">home</Link>
</li>
<li>
<Link to="/about">about</Link>
</li>
</ul>
<Suspense fallback={<div>Loading...</div>}>
<Routes>
<Route path="/home" element={<Home />}></Route>
<Route path="/about" element={<About />}></Route>
</Routes>
</Suspense>
</>
)
}
export default App
import React from 'react'
import ReactDom from 'react-dom/client'
import App from './App'
import {BrowserRouter} from 'react-router-dom'
import 'antd/dist/antd.less'
const root = ReactDom.createRoot(document.getElementById('app'))
root.render(
<BrowserRouter>
<App/>
</BrowserRouter>
)
module.exports = {
extends: ["react-app"], // 继承 react 官方规则
parserOptions: {
babelOptions: {
presets: [
// 解决页面报错问题
["babel-preset-react-app", false],
"babel-preset-react-app/prod",
],
},
},
};
module.exports = {
presets:['react-app'],//使用react的预设
}
"browserslit": [
"last 2 version",
"> 1%",
"not dead"
],
"scripts": {
"start": "npm run dev",
"dev": "cross-env NODE_ENV=development webpack serve --config ./config/webpack.config.js",
"build": "cross-env NODE_ENV=production webpack --config ./config/webpack.config.js"
},
关于react的webpack配置,如君还有优化空间或问题,请在评论区讨论或私聊我,共同努力共同进步。
万分感谢