網站首頁 編程語言 正文
引言
Create React App 是一個官方支持的創建 React 單頁應用程序的方法。它提供了一個零配置的現代構建設置。
雖然開箱即用,但是開發中我們還是少不了做一些修改,下面總結了一些常用的配置。
yarn安裝依賴包報錯
在項目目錄下運行yarn,報錯如下
yarn install v1.7.0
[1/4] Resolving packages...
[2/4] Fetching packages...
info There appears to be trouble with your network connection. Retrying...
error An unexpected error occurred: "https://registry.yarnpkg.com/@babel/highlight/-/highlight-7.0.0.tgz: connect ETIMEDOUT 104.16.21.35:443".
info If you think this is a bug, please open a bug report with the information provided in "F:\\await\\react-rabc\\yarn-error.log".
info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.
提示很明顯,網絡連接超時,我們更換一下源地址就行了
npm 設置為 淘寶源
npm config set registry https://registry.npm.taobao.org
npm config set disturl https://npm.taobao.org/dist
yarn 設置為 淘寶源
yarn config set registry https://registry.npm.taobao.org --global
yarn config set disturl https://npm.taobao.org/dist --global
項目中如果用的是 sass,需要下載 node-sass,這個依賴包下載是相當的慢,可以單獨設置源地址
yarn config set sass-binary-site http://npm.taobao.org/mirrors/node-sass
npm config set sass-binary-site http://npm.taobao.org/mirrors/node-sass
最后刪除 node_modules,重新下載就行了
IE10下報錯, Map 未定義
yarn add react-app-polyfill
入口文件第一行引入
// This must be the first line in src/index.js
import 'react-app-polyfill/ie9'
react-app-polyfill
webpack添加 alias
config/modules.js文件中的webpackAliases的alias是解析項目根目錄下的tsconfig.json或者jsconfig.json來返回的,有點復雜
可以直接在webpack.config.js的resolve.alias字段中的末尾新增字段
resolve: {
// ...
alias: {
// ...
'@': path.resolve(__dirname, '../src')
}
}
解決跨域,反向代理配置
1、安裝依賴
yarn add http-proxy-middleware
2、在src目錄下新建setupProxy.js文件
const { createProxyMiddleware } = require('http-proxy-middleware')
module.exports = function(app) {
app.use(
'/api',
createProxyMiddleware({
target: 'http://localhost:6000', // 請求接口地址
changeOrigin: true,
pathRewrite: {
'^/api': '/'
}
})
)
}
項目主要文件路徑配置
包括項目入口文件、靜態目錄、項目構建輸出目錄、配置proxy文件...
在config/paths.js文件配置,挑出幾個最常用的
module.exports = {
dotenv: resolveApp('.env'), // 項目環境變量文件
appBuild: resolveApp('dist'), // 項目構建輸出目錄,默認 build
appPublic: resolveApp('public'), // 靜態目錄
appHtml: resolveApp('public/index.html'), // index.html
appIndexJs: resolveModule(resolveApp, 'src/index'), // 項目入口文件
proxySetup: resolveApp('src/setupProxy.js') // 配置 proxy 文件
}
關閉自動開啟瀏覽器配置
在scripts/start.js文件,注釋掉openBrowser(urls.localUrlForBrowser)即可,
或者使用環境變量BROWSER
{
"script": {
"start": "cross-env BROWSER=none node scripts/start.js"
}
}
修改 webpack output.publicPath
如果項目不是部署在靜態服務器根目錄下會用到,直接在package.json中配置homepage字段
{ "homepage": "/e-admin/" }
或者使用環境變量PUBLIC_URL
{
"script": {
"build": "cross-env PUBLIC_URL=/e-admin/ node scripts/build.js"
}
}
生產環境關閉 sourcemap
一般在部署到生產環境會關閉 sourcemap,避免打包文件過大
查看 webpack.config.js 看到如下代碼:
const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== 'false';
可以在命令行中使用GENERATE_SOURCEMAP這個環境變量
{
"script": {
"build": "cross-env GENERATE_SOURCEMAP=false node scripts/build.js"
}
}
eslint 配置
可以直接在package.json中的eslintConfig字段配置。
在根目錄下新建.eslint.js(或者.eslintrc)配置文件,然后在命令行中設置EXTEND_ESLINT
{
"script": {
"start": "cross-env EXTEND_ESLINT=true node scripts/start.js"
}
}
因為各平臺設置環境變量的方式不同,這里使用cross-env來抹平差異
裝飾器 Decorators 配置
開發中會有很多高階組件以及 redux 的 connect 來包裹組件,使用 Decorators 寫法會直觀許多
- 先安裝 babel 插件
yarn add @babel/plugin-proposal-decorators
- babel 配置,在 plugins 中添加
{ "plugins": [ [ "@babel/plugin-proposal-decorators", { "legacy": true } ] ] }
完成上面配置后,編譯就不會報錯了,代碼能正常運行,但是編輯器(這是使用VSCode)卻報錯了,我們需要做額外的配置
在根目錄下新建 jsconfig.json 文件
{ "compilerOptions": { "experimentalDecorators": true } }
打開 VSCode 的 setting.json 文件,添加以下屬性
"javascript.implicitProjectConfig.experimentalDecorators": true
create-react-app 的 babel 配置默認是在 package.json 中的,可以單獨放到根目錄下(.babelrc或者babel.config.js)
區分環境
開發環境,測試環境,預生產環境,生產環境,很多配置項(比如接口地址)都是不同的,這時候我們需要根據環境來決定配置項。
create-react-app 默認支持development,test,production,這里的 test 是用來做代碼測試的,并不是構建測試環境的,我們需要多種打包環境。
這里我們先區分三個環境:
- 開發環境 dev
- 測試環境 alpha
- 生產環境 prod
1、然后在根目錄新建三個文件 .env,.env.alpha,.env.prod,文件內容如下:
// .env
NODE_ENV=development
REACT_APP_MODE=dev
// .env.alpha
NODE_ENV=production
REACT_APP_MODE=alpha
// .env.prod
NODE_ENV=production
REACT_APP_MODE=prod
2、修改package.json的命令腳本
{ "script": { "build:alpha": "cross-env MODE_ENV=alpha node scripts/build.js", "build:prod": "cross-env MODE_ENV=prod node scripts/build.js" } }
3、修改config/env.js文件
// const NODE_ENV = process.env.NODE_ENV;
const NODE_ENV = process.env.MODE_ENV || process.env.NODE_ENV;
4、然后在業務代碼里面就可以使用process.env.REACT_APP_MODE來區分環境了
// axios.baseURL
const baseURL = {
dev: 'http://localhost:3000',
alpha: 'http://alpha.xxx.com',
prod: 'http://xxx.com'
}[process.env.REACT_APP_MODE]
根據不同命令區分不同環境,這是通用的手段。
這里根據npm命令中的REACT_APP_MODE來決定使用哪個.env.[xxx]的環境變量,注入到編譯代碼中。
注意:
- 需要注意的是在 env.js 文件中將 NODE_ENV 替換為了 MODE_ENV,導致本來的 NODE_ENV 缺失,在 .env.[xxx] 文件中要補上
- .env.[xxx] 的環境變量 以 REACT_APP_xxx 開頭
編譯進度條配置
安裝依賴
yarn add webpackbar
修改webpack.config.js文件
const WebpackBar = require('webpackbar')
plugins: [
// ...
new webpack.ProgressPlugin(),
new WebpackBar()
]
webpack.ProgressPlugin() 是webpack內置插件,webpack.ProgressPlugin,WebpackBar用來顯示編譯時長
打包開啟 gzip 壓縮
安裝依賴
yarn add compression-webpack-plugin
修改webpack.config.js文件
const CompressionPlugin = require('compression-webpack-plugin')
const isGzip = process.env.GENERATE_GZIP_FILE === 'true'
plugins: [
// ...
isEnvProduction && isGzip && new CompressionPlugin({
filename: '[path].gz[query]', // 新版本 asset 屬性已更換為 filename
algorithm: 'gzip',
test: /\.js$|\.css$/,
threshold: 10240,
minRatio: 0.8
})
]
通過設置環境變量GENERATE_GZIP_FILE=true來啟用gzip壓縮
請確保靜態服務器開啟了 gzip 配置項,nginx 配置 gzip_static on; 選項即可
下面是未開啟gzip和開啟gzip的效果:
未開啟 gzip
開啟 gzip
生成 report.html 可視化打包分析
安裝依賴
yarn add webpack-bundle-analyzer
修改webpack.config.js文件
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer')
const isBundleAnalyzer = process.env.GENERATE_BUNDLE_ANALYZER_REPORT === 'true'
plugins: [
// ...
isEnvProduction && isBundleAnalyzer && new BundleAnalyzerPlugin()
]
通過設置環境變量GENERATE_BUNDLE_ANALYZER_REPORT=true來生成report
引入 antd
antd 的 JS 代碼默認支持基于 ES modules 的 tree shaking,即按需引入,只是樣式的引入有些區別
1、直接引入,樣式直接用編譯后的antd.css
import { Button } from 'antd'
import 'antd/dist/antd.css'
function App() {
return (
<Button type="primary">按鈕</Button>
)
}
簡單粗暴,但是沒法統一修改一些全局的顏色
2、引入 less
安裝依賴
yarn add less less-loader
wepack.config.js配置,默認的rules已經包含css和sass,先找到下面的正則
// style files regexes
const cssRegex = /\.css$/;
const cssModuleRegex = /\.module\.css$/;
const sassRegex = /\.(scss|sass)$/;
const sassModuleRegex = /\.module\.(scss|sass)$/;
// 加上匹配 less 文件的正則
const lessRegex = /\.less$/;
const lessModuleRegex = /\.module\.less$/;
然后加上 loader 配置,在sass-loader配置下面加上less-loader的配置
// Adds support for CSS Modules, but using SASS
// using the extension .module.scss or .module.sass
{
test: sassModuleRegex,
use: getStyleLoaders(
{
importLoaders: 3,
sourceMap: isEnvProduction && shouldUseSourceMap,
modules: {
getLocalIdent: getCSSModuleLocalIdent,
},
},
'sass-loader'
),
},
// 在下面加上 less-loader 配置
{
test: lessRegex,
exclude: lessModuleRegex,
use: getStyleLoaders(
{
importLoaders: 2,
sourceMap: isEnvProduction && shouldUseSourceMap,
},
'less-loader'
),
sideEffects: true,
},
// Adds support for CSS Modules, but using less
// using the extension .module.less
{
test: lessModuleRegex,
use: getStyleLoaders(
{
importLoaders: 2,
sourceMap: isEnvProduction && shouldUseSourceMap,
modules: {
getLocalIdent: getCSSModuleLocalIdent
}
},
'less-loader'
),
},
找到getStyleLoaders方法,做如下修改:
// 將 if (preProcessor) {} 中的代碼替換,實際上就是判斷是`less-loader`就生成針對less的options
if (preProcessor) {
let preProcessorRule = {
loader: require.resolve(preProcessor),
options: {
sourceMap: true
}
}
if (preProcessor === 'less-loader') {
preProcessorRule = {
loader: require.resolve(preProcessor),
options: {
sourceMap: true,
lessOptions: { // 如果使用less-loader@5,需要移除 lessOptions 這一級
javascriptEnabled: true,
modifyVars: {
'primary-color': '#346fff', // 全局主色
'link-color': '#346fff' // 鏈接色
}
}
}
}
}
loaders.push(
{
loader: require.resolve('resolve-url-loader'),
options: {
sourceMap: isEnvProduction && shouldUseSourceMap,
},
},
preProcessorRule
);
}
將import 'antd/dist/antd.css'換成import 'antd/dist/antd.less'
經過上面的配置后,可以直接修改less變量來修改全局顏色、間距等,所有變量
當然如果在配置文件中覆蓋less變量有些麻煩,可以直接直接新建單獨的less文件來覆蓋默認變量
@import '~antd/lib/style/themes/default.less';
@import '~antd/dist/antd.less';
@import 'customer-theme-file.less'; // 用于覆蓋默認變量
但是這種方式會加載所有組件的樣式,沒法做到按需加載
3、按需加載
安裝依賴
yarn add babel-plugin-import
babel 配置
"plugins": [ [ "babel-plugin-import", { "libraryName": "antd", "libraryDirectory": "es", "style": true } ] ]
去掉import 'antd/dist/antd.less'的引入,現在引入組件就會附帶引入對應組件的樣式了
參考鏈接:
Create React App 官方文檔
Create React App 中文文檔
Ant Design
原文鏈接:https://www.jianshu.com/p/36efe1dc2f5e
相關推薦
- 2022-11-03 C++模板超詳細介紹_C 語言
- 2022-06-12 Python利用subplots_adjust方法解決圖表與畫布的間距問題_python
- 2022-05-31 C++核心編程之內存分區詳解_C 語言
- 2022-12-28 React組件的生命周期深入理解分析_React
- 2022-12-12 Python字典使用技巧詳解_python
- 2022-06-12 一文搞懂C語言static關鍵字的三個作用_C 語言
- 2022-07-11 Cadence中denalirc的用法總結
- 2022-04-26 Jquery+bootstrap實現表格行置頂置底上移下移操作詳解_jquery
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支