文章標題
- 01 環境準備
- 02 快速構建
- 2.1 參數選項
- 2.2 umi@x 還是 @umijs/max
- 2.3 使用 pnpm (推薦)
- 2.4 使用 npm 和 yarn
- 2.5 啟動項目
- 2.6 啟用 Prettier(可選)
- 2.7 打包部署發布
- 03 Tailwind CSS 插件(可選)
- 3.1 安裝配置
- 3.2 可能遇到的問題
- 04 React 中的 classnames
- 4.1 安裝
- 4.2 使用
- 參考示例如下
- 在React中使用
01 環境準備
首先得有 node
,并確保 node 版本是 18 或以上。
- windows 下推薦用 nvm 來管理 node 版本(nvm中文文檔)
- mac 下推薦使用 n 來管理 node 版本(npm-n 官方文檔)
安裝 node 👇
# windows: nvm 操作
$ nvm install 18.20.0
$ nvm use 18.20.0
$ node -v
v18.20.0# mac: n 操作
$ sudo n 18.20.0
$ node -v
v18.20.0
還需要包管理工具,node 默認包含 npm
,但也可以選擇其他方案,如:pnpm
、yarn
此處選擇安裝 pnpm👇
# 方式1: 一個普通版本,它需要Node.js來運行。
npm install -g pnpm# 方式2: 與Node.js一起打包成一個可執行文件,所以它可以在沒有安裝Node.js的系統上使用。
npm install -g @pnpm/exe
02 快速構建
2.1 參數選項
使用 create-umi 創建項目時,可用的參數如下:
option(可選參數) | 描述 |
---|---|
–no-git | 創建項目,但不初始化 Git |
–no-install | 創建項目,但不自動安裝依賴 |
2.2 umi@x 還是 @umijs/max
使用 create-umi 選擇 Ant Design Pro
模板,就能使用 @umijs/max
來創建項目了
$ npx create-umi@latest
? Pick Umi App Template ? - Use arrow-keys. Return to submit.Simple App
? Ant Design ProVue Simple App
在 Umi Max 項目中命令行請使用 max{:bash}
,而不是原來的 umi{:bash}
,示例如下 👇
$ npx max g jest
歷史項目升級:如果使用了 @umijs/max
可以使用 max
命令來替換 umi
,如 max dev,max build 等。而 umi@4
將一些項目前置操作放到了 setup
命令中,如 umi@3
中的 umi g tmp
等命令,需要使用 umi setup
替換,示例如下 👇
// package.json
{"scripts": {
- "build": "umi build",
+ "build": "max build",
- "postinstall": "umi g tmp",
+ "postinstall": "max setup",
- "start": "umi dev",
+ "start": "max dev",}
}
詳細升級步驟參考 升級到 Umi 介紹
2.3 使用 pnpm (推薦)
國內建議選 pnpm + taobao 源,速度提升明顯。這一步會自動安裝依賴,同時安裝成功后會自動執行 umi setup
做一些文件預處理等工作。
$ pnpm dlx create-umi@latest
? Install the following package: create-umi? (Y/n) · true
┌ create-umi
│
○ What's the target folder name?
│ my-app
│
○ Pick Umi App Template
│ ● Simple App
│ ○ Ant Design Pro
│ ○ Vue Simple App
│ ○ Umi Plugin
│
○ Pick Npm Client
│ ○ npm
│ ○ cnpm
│ ○ tnpm
│ ○ yarn
│ ● pnpm (recommended)
│
○ Pick Npm Registry
│ ○ npm
│ ● taobao
│
└ You're all set!...Done in 1m 45.8s using pnpm v10.10.0
2.4 使用 npm 和 yarn
# npm
$ npx create-umi@latest
Need to install the following packages:create-umi@latest
Ok to proceed? (y) y
...# yarn
yarn create umi
success Installed "create-umi@4.0.6" with binaries:- create-umi
...
2.5 啟動項目
執行 pnpm dev
命令,在瀏覽器里打開 http://localhost:8000/
,就能看到項目界面
$ pnpm dev
...╔════════════════════════════════════════════════════╗║ App listening at: ║║ > Local: http://localhost:8000 ║
ready - ║ > Network: http://192.168.11.188:8000 ║║ ║║ Now you can open browser with the above addresses↑ ║╚════════════════════════════════════════════════════╝
...
2.6 啟用 Prettier(可選)
如果需要用 prettier
做項目代碼的自動格式化,執行 pnpm umi g
命令
$ pnpm umi g
? Pick generator type ? Enable Prettier -- Enable Prettier
info - Write package.json
info - Write .prettierrc
info - Write .prettierignore
info - Install dependencies with pnpm
2.7 打包部署發布
執行 pnpm build
命令
$ pnpm build
event - compiled successfully in 1179 ms (567 modules)
event - build index.html
打包文件默認會生成到 ./dist
目錄下
./dist
├── index.html
├── umi.css
└── umi.js
完成構建后,就可以把 dist
目錄部署到服務器上了。
03 Tailwind CSS 插件(可選)
3.1 安裝配置
在 Umi 和 Umi Max 項目使用 Tailwind CSS 功能,使用微生成器一鍵開啟該插件
Umi 項目
$ npx umi g tailwindcss
info - Update package.json for devDependencies
set config:tailwindcss on /project/max-playground/.umirc.ts
info - Update .umirc.ts
info - Write tailwind.config.js
info - Write tailwind.css
Umi Max 項目
$ npx max g tailwindcss
info - Update package.json for devDependencies
set config:tailwindcss on /project/max-playground/.umirc.ts
info - Update .umirc.ts
info - Write tailwind.config.js
info - Write tailwind.css
至此就可以在項目中使用 Tailwind CSS 的樣式,并且可以在項目根目錄的 tailwind.config.js
和 tailwind.css
根據需要修改配置。
注意需要同步插件依賴 👇
$ pnpm i
在項目根目錄添加 .env
文件,添加 CHECK_TIMEOUT
變量,用于設置 Tailwind CSS 插件的檢查間隔時間。
# Default: 5
CHECK_TIMEOUT=10
3.2 可能遇到的問題
(1)終端報錯 Unexpected unknown at-rule “@tailwind” at-rule-no-unknown
問題描述:因為 @umijs/max
項目已經添加 husky,并為項目生成 precommit 配置(即 git commit message 格式校驗行為),在每次 git commit
前會將 Git 暫存區的代碼默認格式化。 但使用 vscode 用戶,在 commit 代碼時可能會遇到下面這樣的問題:
tailwind.css1:1 ? Unexpected unknown at-rule "@tailwind" at-rule-no-unknown2:1 ? Unexpected unknown at-rule "@tailwind" at-rule-no-unknown3:1 ? Unexpected unknown at-rule "@tailwind" at-rule-no-unknownhusky - pre-commit script failed (code 1)
問題原因:vscode 編輯器可能識別不了 “@tailwind” 導致 pre-commit 沒有通過
解決方案1:找到 .husky
下的 pre-commit
文件進行刪除
解決方案2:在 commit 時加上 --no-verify
參數繞過檢查
git commit -m "xxx" --no-verify
解決方案3: https://github.com/tailwindlabs/tailwindcss/discussions/5258
1.在項目的根目錄下創建 .vscode
,并用兩個名為 settings.json
、tailwind.json
2.更新 settings.json
和 tailwind.json
文件
// settings.json
{"css.customData": [".vscode/tailwind.json"],// (識別您正在使用的文件類型,例如css)"css.lint.unknownAtRules": "ignore"
}// tailwind.json
{"version": 1.1,"atDirectives": [{"name": "@tailwind","description": "Use the `@tailwind` directive to insert Tailwind's `base`, `components`, `utilities` and `screens` styles into your CSS.","references": [{"name": "Tailwind Documentation","url": "https://tailwindcss.com/docs/functions-and-directives#tailwind"}]},{"name": "@apply","description": "Use the `@apply` directive to inline any existing utility classes into your own custom CSS. This is useful when you find a common utility pattern in your HTML that you’d like to extract to a new component.","references": [{"name": "Tailwind Documentation","url": "https://tailwindcss.com/docs/functions-and-directives#apply"}]},{"name": "@responsive","description": "You can generate responsive variants of your own classes by wrapping their definitions in the `@responsive` directive:\n```css\n@responsive {\n .alert {\n background-color: #E53E3E;\n }\n}\n```\n","references": [{"name": "Tailwind Documentation","url": "https://tailwindcss.com/docs/functions-and-directives#responsive"}]},{"name": "@screen","description": "The `@screen` directive allows you to create media queries that reference your breakpoints by **name** instead of duplicating their values in your own CSS:\n```css\n@screen sm {\n /* ... */\n}\n```\n…gets transformed into this:\n```css\n@media (min-width: 640px) {\n /* ... */\n}\n```\n","references": [{"name": "Tailwind Documentation","url": "https://tailwindcss.com/docs/functions-and-directives#screen"}]},{"name": "@variants","description": "Generate `hover`, `focus`, `active` and other **variants** of your own utilities by wrapping their definitions in the `@variants` directive:\n```css\n@variants hover, focus {\n .btn-brand {\n background-color: #3182CE;\n }\n}\n```\n","references": [{"name": "Tailwind Documentation","url": "https://tailwindcss.com/docs/functions-and-directives#variants"}]}]
}
04 React 中的 classnames
classnames
是一個強大的工具,可以幫助你在 React 項目中更優雅地處理 className。通過它,你可以輕松地根據條件動態生成 className,從而使代碼更加簡潔和易讀。它還支持混合對象、數組和字符串參數,使得支持可選的 className 屬性更加簡單。通過使用 classnames
,你可以避免手動拼接字符串,從而減少錯誤并提高代碼的可維護性。
4.1 安裝
$ npm install classnames
# 或者
$ yarn add classnames
# 或者
$ pnpm i classnames
4.2 使用
參考示例如下
// classNames函數接受任意數量的參數,這些參數可以是字符串或對象
classNames('foo', 'bar'); // => 'foo bar'
classNames('foo', { bar: true }); // => 'foo bar'
classNames({ 'foo-bar': true }); // => 'foo-bar'
classNames({ 'foo-bar': false }); // => ''
classNames({ foo: true }, { bar: true }); // => 'foo bar'
classNames({ foo: true, bar: true }); // => 'foo bar'
classNames('foo', { bar: true, duck: false }, 'baz', { quux: true }); // => 'foo bar baz quux'
classNames(null, false, 'bar', undefined, 0, 1, { baz: null }, ''); // => 'bar 1'
// 數組也可以按照上述規則遞歸平展:
const arr = ['b', { c: true, d: false }];
classNames('a', arr); // => 'a b c'
在React中使用
import React, { useState } from 'react';
import classNames from 'classnames';export default function Test() {return (<><div className={classNames('foo', 'bar')}>classNames基礎使用實例</div><div className={classNames('foo', 'bar')}><span> classNames+TailwindCss 使用實例</span><span className={classNames('title', '!text-red-600')}>單獨為特定原子化CSS增加"!"前輟讓它生成的原子化CSS添加"!important"后輟來提高樣式優先級</span></div> </>
);
}
參考 Umijs官網