React + Umi(Umijs/Max) 搭建项目及配置
文章标题
- 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官网