react webpack配置

接上期 webpack的基础配置
同样附上个人git仓库地址:https://gitee.com/zhaosir1/webpack-base-react-cli.git
详细注释请参考:webpack的基础配置 https://blog.csdn.net/qq_45142260/article/details/125345042
废话不多说,直接上代码

  1. 目录结构

  2. 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)}}]},// 处理htmlplugins:[// 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文件的copyisProduction && 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的pluginmode: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,//关闭性能分析,提升打包速度
}
  1. App.js
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
  1. main.js
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>
)
  1. .eslintrc.js
module.exports = {extends: ["react-app"], // 继承 react 官方规则parserOptions: {babelOptions: {presets: [// 解决页面报错问题["babel-preset-react-app", false],"babel-preset-react-app/prod",],},},
};
  1. babel.config.js
module.exports = {presets:['react-app'],//使用react的预设
}
  1. package.json
"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配置,如君还有优化空间或问题,请在评论区讨论或私聊我,共同努力共同进步。
万分感谢

react webpack配置相关推荐

  1. Flask + Nginx + React + Webpack 配置解决跨域问题

    用 Flask 做后端开发单页应用,webpack-dev-server 生成静态文件在http://localhost:8080 下,Flask 页面在 http://localhost:5000 ...

  2. react webpack配置组件路径引用 @与自定义

    暴露配置文件: create-react-app 生成的项目看不到 webpack 相关的配置文件,需要先暴露出来,使用如下命令 npm run eject 修改配置文件: webpack.confi ...

  3. react webpack配置 paths.js

    'use strict';const path = require('path'); const fs = require('fs'); const getPublicUrlOrPath = requ ...

  4. 使用webpack配置react并添加到flask应用

    学习react,配置是很痛苦的一关,虽然现在有了create-react-app这样方便的工具,但是必须要自己配置一遍,才能更好地进行项目开发. 首先要明确一个概念:react的文件必须经过编译才能被 ...

  5. 修改webpack配置,在react中使用less

    LESS是一个CSS预处理器,比如antD就是基于LESS的. 要在react中使用LESS,需要暴露webpack配置并进行修改,同时安装less和less-loader. 当然网上可以找到很多教程 ...

  6. react修改webpack配置,添加别名

    第一种方式 通过 npm run eject 直接暴露出来react所有的webpack配置文件,暴露出来之后,过程不可逆 而且失去了 react-scripts 的统一管理的好处,而且react的w ...

  7. React 不用eject下修改webpack配置实现alisa

    使用 customize-cra 和 react-app-rewired 对React项目进行webpack配置的注入 yarn add customize-cra react-app-rewired ...

  8. 不暴露 create react app 的webpack配置下,修改webpack配置

    使用 react-app-rewired react-app-rewired 传送门 安装 react-app-rewired npm install react-app-rewired --save ...

  9. react+webpack项目常用的插件(plugins)

    一.HtmlWebpackPlugin使用: npm install html-webpack-plugin --save-dev 解释:这个插件是简化创建生成html(h5)文件用的,如果你引入的文 ...

最新文章

  1. (总结)CentOS 6.x使用yum快速安装Apache+PHP+Tomcat(JSP)+MySQL
  2. Android的自定义键盘颜色,android自定义键盘(解决弹出提示的字体颜色问题)
  3. 奔跑吧Linux内核 入门篇(第二版)遇到问题发
  4. 以脚本方式直接执行修改密码的passwd命令
  5. javascript 编译与执行过程
  6. 苹果春季新品发布会来了:将推iPhone13 Pro系列紫色版
  7. .git文件过大,如何清理
  8. 火车票_ _购买卧铺下铺的总结
  9. csu1671 经营小卖部(DP 完全背包 好题)
  10. 再说System Verilog 与 Verilog 的关系
  11. Android一步一步实现一款实用的Android广告栏
  12. 2021年三季度中国家居用品行业A股上市企业营收排行榜:欧派家居、顾家家居排名前2位,且近五年第三季度的净利润均逐年递增(附热榜TOP61详单)
  13. 数学故事在小学数学课堂教学中的应用研究
  14. 大众点评网谈成功秘诀:明白用户感兴趣、需要和寻找的是什么
  15. 嵌入式系统设计 (考试题+答案)
  16. linux远程连接ssh服务和http的深入介绍
  17. 智慧职教云Java题库_智慧职教云课堂Java编码技术题库及答案
  18. js逆向之携程酒店房价抓取
  19. 【考研笔记】数学一 · 高等数学笔记
  20. web 完整轮播图 前端 轮播图 详细

热门文章

  1. dp 这个单位是安卓发明的么?为什么 px=dp*(dpi/160)?
  2. spring boot test 异常之 could not initialize proxy [*Money#31] - no Session
  3. jquery dataTable 参数详解
  4. 手游大话藏宝阁找不到服务器,大话西游手游藏宝阁指定交易在哪里 藏宝阁怎么没有指定我...
  5. 敲响OO时代的丧钟——DJ中的事件机制(重写)
  6. 因为铂金Birkin包 爱马仕把数字艺术家告了
  7. SQL 全文检索应用
  8. [图像] 金字塔模型
  9. 什么是promise,promise的用法。
  10. wps office只显示一级目录和添加水印