### Install and Start UmiJS Development Server
Source: https://github.com/umijs/umi/blob/master/docs/README.md
Install dependencies, start the development server, and build the documentation for UmiJS.
```bash
pnpm install
```
```bash
pnpm start
```
```bash
pnpm run build
```
--------------------------------
### Install dependencies and build
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/introduce/contributing.en-US.md
Install project dependencies and perform an initial build.
```bash
$ pnpm i && pnpm build
```
--------------------------------
### Start Umi documentation development
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/introduce/contributing.en-US.md
Run this command in the root directory to start the documentation development server.
```bash
# Start Umi document development
# Compilation takes longer on first launch, please be patient
$ pnpm docs:dev
```
--------------------------------
### Run examples for testing
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/introduce/contributing.en-US.md
Commands to run specific examples or enable Vite mode for development.
```bash
$ cd examples/boilerplate
$ pnpm dev
```
```bash
$ pnpm dev --vite
```
--------------------------------
### Start Development Server (esbuild)
Source: https://github.com/umijs/umi/blob/master/examples/mfsu-independent/README.md
Starts the development server using the esbuild transpiler.
```bash
pnpm dev:esbuild
```
--------------------------------
### Start Development Server (Babel)
Source: https://github.com/umijs/umi/blob/master/examples/mfsu-independent/README.md
Starts the development server using the Babel transpiler.
```bash
pnpm dev
```
--------------------------------
### Build Example with Utoopack
Source: https://github.com/umijs/umi/blob/master/examples/with-utoopack-istanbul/README.md
Build the example project using pnpm to trigger the utoopack bundler with the configured Babel plugins.
```bash
pnpm --filter @example/with-utoopack-istanbul build
```
--------------------------------
### Install ESLint and Stylelint
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/guides/lint.md
Install ESLint and a compatible version of Stylelint as development dependencies.
```bash
npm i -D eslint "stylelint@^14"
# or
pnpm add -D eslint "stylelint@^14"
```
--------------------------------
### Initialize Project Setup
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/api/commands.md
The `umi setup` command initializes your project, often used for generating temporary files. It's typically configured in `package.json`'s `scripts.postinstall`.
```json
{
"scripts": { "postinstall": "umi setup" }
}
```
--------------------------------
### Install dynamic-import-node for Production
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/introduce/faq.md
Install the babel plugin for dynamic imports and configure it to be active only during production builds.
```bash
pnpm i babel-plugin-dynamic-import-node -D
```
```typescript
// .umirc.ts
export default {
extraBabelPlugins: process.env.NODE_ENV === 'production'
? ['babel-plugin-dynamic-import-node']
: []
}
```
--------------------------------
### Start development compilation
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/introduce/contributing.en-US.md
Commands to start the development compiler for the entire project or a specific package.
```bash
$ pnpm dev
```
```bash
$ cd packages/umi
$ pnpm dev
```
--------------------------------
### Get Umi Version
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/api/commands.md
Displays the currently installed version of Umi. This is equivalent to running `umi -v`.
```bash
$ umi version
4.0.0
```
--------------------------------
### Install nvm and Node.js
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/guides/prepare.en-US.md
Installs Node.js version 18 using nvm. Ensure nvm is installed first.
```bash
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash
nvm -v
0.39.1
```
```bash
nvm install 18
nvm use 18
```
```bash
node -v
v18.14.0
```
--------------------------------
### Start Local Development Server
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/api/commands.en-US.md
The `dev` command starts a local development server, providing a live preview of your project during development and debugging.
```bash
$ umi dev
╔═════════════════════════════════════════════════════╗
║ App listening at: ║
║ > Local: https://127.0.0.1:8001 ║
ready - ║ > Network: https://192.168.1.1:8001 ║
║ ║
║ Now you can open browser with the above addresses👆
╚═════════════════════════════════════════════════════╝
event - compiled successfully in 1051 ms (416 modules)
```
--------------------------------
### Install nvm and Node.js
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/guides/getting-started.en-US.md
Install Node Version Manager (nvm) and then install and use Node.js version 18 or above. This is a prerequisite for UmiJS development.
```bash
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash
nvm -v
0.39.1
```
```bash
nvm install 18
nvm use 18
node -v
v18.10.0
```
--------------------------------
### Install Vue Preset
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/guides/use-vue.en-US.md
Install the Vue preset for UmiJS using pnpm.
```bash
pnpm add @umijs/preset-vue -D
```
--------------------------------
### Install Dependencies with pnpm
Source: https://github.com/umijs/umi/blob/master/examples/mfsu-independent/README.md
Run this command to install project dependencies using pnpm.
```bash
pnpm install
```
--------------------------------
### Install pnpm
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/guides/prepare.md
Install pnpm, a recommended package manager for Umi.js projects, using its official installation script.
```bash
curl -fsSL https://get.pnpm.io/install.sh | sh -
```
```bash
pnpm -v
7.3.0
```
--------------------------------
### Environment Variables Example
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/guides/directory-structure.en-US.md
Example of setting environment variables for Umi projects. These can be used to configure runtime settings like the port or compression.
```text
PORT=8888
COMPRESS=none
```
--------------------------------
### Build Example with pnpm
Source: https://github.com/umijs/umi/blob/master/examples/with-utoopack-externals/README.md
Build the example project using pnpm to verify the externalization configuration. The generated bundle should externalize lodash deep imports.
```bash
pnpm --filter @example/with-utoopack-externals build
```
--------------------------------
### Install Vue Preset
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/guides/use-vue.md
Install the Vue preset for Umi to enable Vue support. This is a development dependency.
```bash
pnpm add @umijs/preset-vue -D
```
--------------------------------
### Install MFSU Dependency
Source: https://github.com/umijs/umi/blob/master/docs/docs/blog/mfsu-independent-usage.md
Install the MFSU package as a development dependency.
```bash
pnpm add -D @umijs/mfsu
```
--------------------------------
### Install and Enable React Query in Umi
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/max/react-query.md
Install the `@umijs/plugins` dependency and enable react-query via the `plugins` and `reactQuery` configuration in `config.ts`.
```bash
$ pnpm i @umijs/plugins -D
```
```typescript
export default {
plugins: ['@umijs/plugins/dist/react-query'],
reactQuery: {},
}
```
--------------------------------
### Install Umi Plugins
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/guides/use-plugins.en-US.md
Install the necessary plugin package using pnpm. This command adds the plugins as a development dependency.
```bash
pnpm add -D @umijs/plugins
```
--------------------------------
### Complete Runtime Request Configuration Example
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/max/request.md
This example demonstrates a full runtime configuration, including error handling strategies, request/response interceptors, and common request settings. It's useful for setting up personalized request logic.
```typescript
import { RequestConfig } from './request';
// 错误处理方案: 错误类型
enum ErrorShowType {
SILENT = 0,
WARN_MESSAGE = 1,
ERROR_MESSAGE = 2,
NOTIFICATION = 3,
REDIRECT = 9,
}
// 与后端约定的响应数据格式
interface ResponseStructure {
success: boolean;
data: any;
errorCode?: number;
errorMessage?: string;
showType?: ErrorShowType;
}
// 运行时配置
export const request: RequestConfig = {
// 统一的请求设定
timeout: 1000,
headers: {'X-Requested-With': 'XMLHttpRequest'},
// 错误处理: umi@3 的错误处理方案。
errorConfig: {
// 错误抛出
errorThrower: (res: ResponseStructure) => {
const { success, data, errorCode, errorMessage, showType } = res;
if (!success) {
const error: any = new Error(errorMessage);
error.name = 'BizError';
error.info = { errorCode, errorMessage, showType, data };
throw error; // 抛出自制的错误
}
},
// 错误接收及处理
errorHandler: (error: any, opts: any) => {
if (opts?.skipErrorHandler) throw error;
// 我们的 errorThrower 抛出的错误。
if (error.name === 'BizError') {
const errorInfo: ResponseStructure | undefined = error.info;
if (errorInfo) {
const { errorMessage, errorCode } = errorInfo;
switch (errorInfo.showType) {
case ErrorShowType.SILENT:
// do nothing
break;
case ErrorShowType.WARN_MESSAGE:
message.warn(errorMessage);
break;
case ErrorShowType.ERROR_MESSAGE:
message.error(errorMessage);
break;
case ErrorShowType.NOTIFICATION:
notification.open({
description: errorMessage,
message: errorCode,
});
break;
case ErrorShowType.REDIRECT:
// TODO: redirect
break;
default:
message.error(errorMessage);
}
}
} else if (error.response) {
// Axios 的错误
// 请求成功发出且服务器也响应了状态码,但状态代码超出了 2xx 的范围
message.error(`Response status:${error.response.status}`);
} else if (error.request) {
// 请求已经成功发起,但没有收到响应
// \`error.request\` 在浏览器中是 XMLHttpRequest 的实例,
// 而在node.js中是 http.ClientRequest 的实例
message.error('None response! Please retry.');
} else {
// 发送请求时出了点问题
message.error('Request error, please retry.');
}
},
},
// 请求拦截器
requestInterceptors: [
(config) => {
// 拦截请求配置,进行个性化处理。
const url = config.url.concat('?token = 123');
return { ...config, url};
}
],
// 响应拦截器
responseInterceptors: [
(response) => {
// 拦截响应数据,进行个性化处理
const { data } = response;
if(!data.success){
message.error('请求失败!');
}
return response;
}
]
};
```
--------------------------------
### Run Utoopack Error Overlay Commands
Source: https://github.com/umijs/umi/blob/master/examples/with-utoopack-error-overlay/README.md
Commands to start the development server and toggle the error state for testing the overlay.
```bash
pnpm dev
pnpm trigger:error
pnpm fix:error
```
--------------------------------
### Install Node Modules
Source: https://github.com/umijs/umi/blob/master/examples/antd-pro-create/README.md
Install project dependencies using npm or yarn.
```bash
npm install
```
```bash
yarn
```
--------------------------------
### Install Stylus Preprocessor
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/guides/styling.en-US.md
Command to install the necessary dependency for using .styl and .stylus files in Umi projects.
```bash
# .styl and .stylus
npm add -D stylus
```
--------------------------------
### Install Pro Components Packages
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/max/charts.md
Install specific Pro Components packages like Pro Table or Pro List as needed for your project.
```bash
# 引入高级表格
pnpm install @ant-design/pro-table
# 引入高级列表
pnpm install @ant-design/pro-list
```
--------------------------------
### Start Ant Design Pro Project
Source: https://github.com/umijs/umi/blob/master/examples/antd-pro-create/README.md
Run this script to start the development server for your Ant Design Pro project.
```bash
npm start
```
--------------------------------
### Install and Enable React Query in Umi
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/max/react-query.en-US.md
For older umi versions, first install the @umijs/plugins dependency, then enable react-query through configuration.
```bash
$ pnpm i @umijs/plugins -D
```
--------------------------------
### Install Dependencies for Prisma, Bcrypt, and JWT
Source: https://github.com/umijs/umi/blob/master/docs/docs/blog/develop-blog-using-umi.en-US.md
Install necessary packages for database interaction with Prisma, password hashing with bcryptjs, and authentication with jsonwebtoken.
```shell
pnpm i -d prisma @types/bcryptjs @types/jsonwebtoken
pnpm i @prisma/client bcryptjs jsonwebtoken
```
--------------------------------
### Umi 4 Configuration Example
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/introduce/upgrade-to-umi-4.en-US.md
Example configuration for Umi 4 using defineConfig, including settings for model, antd, request, initialState, mock, dva, and layout.
```typescript
import { defineConfig, utils } from 'umi';
export default defineConfig({
model: {},
antd: {},
request: {},
initialState: {},
mock: {
include: ['src/pages/**/_mock.ts'],
},
dva: {},
layout: {
// https://umijs.org/docs/max/layout-menu#configuration-at-build-time
title: 'UmiJS',
locale: true,
},
// https://umijs.org/zh-CN/plugins/plugin-locale
locale: {
// default zh-CN
default: 'zh-CN',
antd: true,
// default true, when it is true, will use `navigator.language` overwrite default
baseNavigator: true,
},
});
```
--------------------------------
### Micro App Routing Example
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/max/micro-frontend.md
Example of configuring a micro-app route within the main application. This specifies the path, the micro-app name, and optional micro-app properties.
```js
{
path: '/app1',
microApp: 'app1',
}
```
--------------------------------
### Install and Enable styled-components in UmiJS
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/max/styled-components.en-US.md
For older Umi versions, install the `@umijs/plugins` dependency and then enable styled-components via configuration.
```bash
$ pnpm i @umijs/plugins -D
```
```typescript
export default {
plugins: ['@umijs/plugins/dist/styled-components'],
styledComponents: {},
}
```
--------------------------------
### Configuring transform-runtime
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/api/config.en-US.md
Setting up the transform-runtime plugin and installing the required dependency.
```js
transformRuntime: {
absoluteRuntime: process.cwd(),
}
```
```bash
$ npm install @babel/runtime --save-dev
```
--------------------------------
### Example: Registering and Calling a Custom Method
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/api/plugin-api.en-US.md
Demonstrates registering a 'foo' method with a function and then calling it with an argument.
```typescript
api.registerMethod({
name: foo,
// has fn
fn: (args) => {
console.log(args);
}
})
api.foo('hello, umi!'); // hello, umi!
```
--------------------------------
### Install Ant Design Charts Package
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/max/charts.en-US.md
Install the complete Ant Design Charts package using pnpm.
```bash
pnpm install @ant-design/charts
```
--------------------------------
### Install Ant Design Pro List
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/max/charts.en-US.md
Install the advanced list component from Ant Design Pro Components.
```bash
pnpm install @ant-design/pro-list
```
--------------------------------
### Start Local Development with SOCKET_SERVER
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/guides/debug.en-US.md
When using XSwitch to debug local code on a live project address, start your local Umi development server with the SOCKET_SERVER environment variable set to prevent continuous page refreshes.
```bash
$SOCKET_SERVER=http://127.0.0.1:8000/ npx umi dev
```
--------------------------------
### Example: Registering a Method with a Function
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/api/plugin-api.md
This example demonstrates registering a 'foo' method on the API that logs its arguments to the console when called.
```typescript
api.registerMethod({
name: foo,
// 有 fn
fn: (args) => {
console.log(args);
}
})
api.foo('hello, umi!'); // hello, umi!
```
--------------------------------
### Install Umi Lint and Dependencies
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/guides/lint.en-US.md
Install the `@umijs/lint` package and necessary peer dependencies like `eslint` and `stylelint` for Umi projects. For Umi Max, linting is built-in.
```bash
$ npm i @umijs/lint -D
# or
$ pnpm add @umijs/lint -D
```
```bash
$ npm i -D eslint "stylelint@^14"
# or
$ pnpm add -D eslint "stylelint@^14"
```
--------------------------------
### Generate Prettier Configuration
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/guides/generator.en-US.md
Generate a recommended Prettier configuration and install necessary dependencies for your project.
```bash
$umi g prettier
info - Write package.json
info - Write .prettierrc
info - Write .prettierignore
```
--------------------------------
### Umi 4 Configuration Example
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/introduce/upgrade-to-umi-4.md
Example of a Umi 4 configuration file (`config/config.ts`) using `defineConfig` and enabling common features like `model`, `antd`, `request`, `initialState`, `mock`, `dva`, and `layout`.
```typescript
import { defineConfig, utils } from 'umi';
export default defineConfig({
model: {},
antd: {},
request: {},
initialState: {},
mock: {
include: ['src/pages/**/_mock.ts'],
},
dva: {},
layout: {
// https://umijs.org/docs/max/layout-menu#构建时配置
title: 'UmiJS',
locale: true,
},
// https://umijs.org/zh-CN/plugins/plugin-locale
locale: {
// default zh-CN
default: 'zh-CN',
antd: true,
// default true, when it is true, will use `navigator.language` overwrite default
baseNavigator: true,
},
});
```
--------------------------------
### Start UmiJS Development Server
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/guides/getting-started.en-US.md
Run the `pnpm dev` command to start the UmiJS development server. This command compiles the project and provides local and network URLs for accessing the application.
```bash
pnpm dev
╔═════════════════════════════════════════════════════╗
║ App listening at: ║
║ > Local: https://127.0.0.1:8000 ║
ready - ║ > Network: https://192.168.1.1:8000 ║
║ ║
║ Now you can open a browser with the above addresses👆 ║
╚═════════════════════════════════════════════════════╝
event - compiled successfully in 1121 ms (388 modules)
event - MFSU compiled successfully in 1308 ms (875 modules)
```
--------------------------------
### addOnDemandDeps
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/api/plugin-api.md
Adds on-demand dependencies that are checked for installation when the project starts. The callback function should return an array of dependency objects.
```APIDOC
## addOnDemandDeps
Adds on-demand dependencies, which will be checked for installation when the project starts:
```ts
api.addOnDemandDeps(() => [{ name: '@swc/core', version: '^1.0.0', dev: true }])
```
```
--------------------------------
### Umi Plugin API Example
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/guides/directory-structure.en-US.md
Provides an example of a project-level Umi plugin using the `IApi` interface to hook into build and modification events.
```typescript
import type { IApi } from 'umi';
export default (api: IApi) => {
api.onDevCompileDone((opts) => {
opts;
// console.log('> onDevCompileDone', opts.isFirstCompile);
});
api.modifyHTML(($) => {
$;
});
api.chainWebpack((memo) => {
memo;
});
};
```
--------------------------------
### Configure API Proxy
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/guides/proxy.en-US.md
Configure proxy settings for API requests. This example proxies requests starting with '/api' to a target server, rewriting the path and changing the origin.
```typescript
export default {
proxy: {
'/api': {
'target': 'http://jsonplaceholder.typicode.com/',
'changeOrigin': true,
'pathRewrite': { '^/api' : '' },
},
},
}
```
--------------------------------
### Create UmiJS Project with Yarn
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/guides/getting-started.en-US.md
Create a new UmiJS project using `yarn create umi`. This command ensures `create-umi` is installed and then proceeds with project setup.
```bash
yarn create umi
success Installed "create-umi@4.0.6" with binaries:
- create-umi
✔ Pick Umi App Template › Simple App
✔ Pick Npm Client › yarn
✔ Pick Npm Registry › taobao
Write: .gitignore
Write: .npmrc
Write: .umirc.ts
Write: package.json
Copy: src/assets/yay.jpg
Copy: src/layouts/index.less
Write: src/layouts/index.tsx
Copy: src/pages/docs.tsx
Copy: src/pages/index.tsx
Write: tsconfig.json
Copy: typings.d.ts
yarn install v1.22.18
success Saved lockfile.
$ umi setup
info - generate files
```
--------------------------------
### Create a new package
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/introduce/contributing.en-US.md
Use these commands to initialize a new package directory and set up development environment.
```bash
# Create package directory
$ mkdir packages/foo
# Initialize package development
$ pnpm bootstrap
```
--------------------------------
### Add On-Demand Dependencies
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/api/plugin-api.md
Use to add dependencies that will be checked for installation when the project starts. The function should return an array of dependency objects, each with 'name', 'version', and optional 'dev' properties.
```typescript
api.addOnDemandDeps(() => [{ name: '@swc/core', version: '^1.0.0', dev: true }])
```
--------------------------------
### Get MFSU Command Help
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/api/commands.md
Use this command to view available options and usage for the mfsu command.
```bash
$ umi mfsu
```
--------------------------------
### Handle Dependency Missing Error
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/guides/mfsu.md
Troubleshoot 'filePath not found' errors in MFSU's 'eager' strategy by ensuring all necessary dependencies, like 'lodash.capitalize' in the example, are installed in your project.
```bash
error - [MFSU][eager] build worker failed AssertionError [ERR_ASSERTION]: filePath not found of lodash.capitalize
```
--------------------------------
### Preview Production Build Locally
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/api/commands.md
The `umi preview` command starts a local static web server to preview your production build. You can configure the port and host, and it respects proxy and mock settings.
```bash
umi preview --port 9527
```
```bash
now `preview` command will run the server on http://127.0.0.1:9527.
Through the `--host` parameter to specify the configuration service running hostname.
The following user configurations will also take effect when `preview`:
* [https](./config#https)
* [proxy](../guides/proxy)
* [mock](../guides/mock)
Note that the `dist` directory will change with the configuration of `outputPath`.
```
--------------------------------
### Update npm Scripts for Umi 4
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/introduce/upgrade-to-umi-4.en-US.md
Replace 'umi' commands with 'max' in package.json scripts for build, postinstall, and start. The 'umi g tmp' command is replaced by 'max setup'.
```json
{
"scripts": {
- "build": "umi build",
+ "build": "max build",
- "postinstall": "umi g tmp",
+ "postinstall": "max setup",
- "start": "umi dev",
+ "start": "max dev"
}
}
```
--------------------------------
### Build Umi documentation
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/introduce/contributing.en-US.md
Execute this command in the root directory to build the documentation for production.
```bash
$ pnpm docs:build
```
--------------------------------
### Create Umi Max Project with Ant Design Pro Template
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/max/introduce.en-US.md
Use `create-umi` with the 'Ant Design Pro' template to start a new Umi Max project. This command-line interface guides you through template selection.
```bash
npx create-umi@latest
? Pick Umi App Template › - Use arrow-keys. Return to submit.
Simple App
❯ Ant Design Pro
Vue Simple App
```
--------------------------------
### Layout Configuration Example
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/guides/directory-structure.en-US.md
Demonstrates how to disable the global layout for specific routes or apply wrapper components for nested layouts.
```jsx
[
{ path: '/', component: '@/pages/index' },
{ path: '/users', component: '@/pages/users' },
]
```
```jsx
index
users
```
```typescript
routes: [
{ path: '/', component: './index', layout: false },
{
path: '/users',
component: './users',
wrappers: ['@/wrappers/auth']
}
]
```
--------------------------------
### Dynamically Switch Global Configuration
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/max/antd.md
Dynamically get and modify Ant Design's ConfigProvider settings using useAntdConfig and useAntdConfigSetter hooks. This example demonstrates switching between dark and default themes for antd v5. Requires configProvider to be enabled.
```typescript
import { Layout, Space, Button, version, theme, MappingAlgorithm } from 'antd';
import { useAntdConfig, useAntdConfigSetter } from 'umi';
const { darkAlgorithm, defaultAlgorithm } = theme;
export default function Page() {
const setAntdConfig = useAntdConfigSetter();
const antdConfig = useAntdConfig();
return (
with antd@{version}
isDarkTheme
{
// 此配置会与原配置深合并
setAntdConfig({
theme: {
algorithm: [
data ? darkAlgorithm : defaultAlgorithm,
],
},
});
// or
setAntdConfig((config) => {
const algorithm = config.theme!.algorithm as MappingAlgorithm[];
if (algorithm.includes(darkAlgorithm)) {
config.theme!.algorithm = [defaultAlgorithm]
} else {
config.theme!.algorithm = [darkAlgorithm];
}
return config;
});
}}
>
);
}
```
--------------------------------
### Preview Production Build with Custom Port
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/api/commands.en-US.md
Launches a local static web server to preview the production build. Supports proxy and mock settings. Use `--port` to specify the running port.
```bash
$ umi preview --port 9527
```
--------------------------------
### List All Umi Commands
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/api/commands.md
Run `umi help` to see a list of all available commands and their brief descriptions. Use `umi help ` for detailed information on a specific command.
```bash
umi help
```
--------------------------------
### Build Project for Production
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/api/commands.en-US.md
Use the `build` command to compile your project for deployment in a production environment.
```bash
$ umi build
```
--------------------------------
### Install @ant-design/maps
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/max/charts.md
Install the @ant-design/maps package to use map-related charting components.
```bash
pnpm install @ant-design/maps
```
--------------------------------
### Create a New Umi Project
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/guides/boilerplate.en-US.md
Use this command to initialize a new Umi project. You will be prompted to choose an npm client and registry.
```bash
pnpm create umi
pnpm create umi my-umi-app
```
--------------------------------
### Install pnpm
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/guides/prepare.en-US.md
Installs the pnpm package manager. This is recommended for Umi.js projects.
```bash
curl -fsSL https://get.pnpm.io/install.sh | sh -
```
```bash
pnpm -v
7.3.0
```
--------------------------------
### Install React 17 for Older Rendering
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/guides/mpa.en-US.md
If React 17 rendering methods are required, install `react@17` and `react-dom@17` in your project. UmiJS will automatically adapt to the installed React version.
```bash
$ pnpm i react@17 react-dom@17
```
--------------------------------
### Configuring Routes with Layout and Wrappers
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/guides/directory-structure.md
Example of route configuration in Umi, demonstrating how to disable layout for a specific route and apply wrappers for authentication.
```ts
routes: [
{ path: '/', component: './index', layout: false },
{
path: '/users',
component: './users',
wrappers: ['@/wrappers/auth']
}
]
```
--------------------------------
### Start Local Development Server
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/api/commands.md
Launch the local development server with `umi dev`. This command provides a hot-reloading environment for efficient development and debugging.
```bash
umi dev
╔═════════════════════════════════════════════════════╗
║ App listening at: ║
║ > Local: https://127.0.0.1:8001 ║
ready - ║ > Network: https://192.168.1.1:8001 ║
║ ║
║ Now you can open browser with the above addresses👆
╚═════════════════════════════════════════════════════╝
event - compiled successfully in 1051 ms (416 modules)
```
--------------------------------
### Configure MFSU Settings
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/api/config.en-US.md
Enable esbuild for faster startup or disable MFSU functionality entirely.
```js
// Use esbuild for dependency pre-compilation
mfsu: {
esbuild: true,
}
// Disable mfsu functionality
mfsu: false;
```
--------------------------------
### Install Ant Design Statistical Chart Package
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/max/charts.en-US.md
Install only the statistical chart sub-package using pnpm.
```bash
pnpm install @ant-design/plots
```
--------------------------------
### Install babel-plugin-dynamic-import-node
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/introduce/faq.en-US.md
Install the dynamic import node plugin for Babel. This is a dependency for disabling dynamic imports.
```bash
pnpm i babel-plugin-dynamic-import-node -D
```
--------------------------------
### Format Umi documentation
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/introduce/contributing.en-US.md
Execute this command in the root directory to format existing documentation files.
```bash
$ pnpm format:docs
```
--------------------------------
### Omit Request Method for GET Requests
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/guides/mock.en-US.md
For GET requests, the method part can be omitted, and only the path is required.
```typescript
// ./mock/users.ts
export default {
'/api/users': [
{ id: 1, name: 'foo' },
{ id: 2, name: 'bar' }
],
'/api/users/1': { id: 1, name: 'foo' },
}
```
--------------------------------
### Configure automatic icon installation
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/api/config.en-US.md
Enable the icons feature with automatic installation support in the Umi configuration file.
```ts
icons: { autoInstall: {} },
```
--------------------------------
### Install Ant Design Pro Table
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/max/charts.en-US.md
Install the advanced table component from Ant Design Pro Components.
```bash
pnpm install @ant-design/pro-table
```
--------------------------------
### On-demand Startup with MPA_FILTER
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/guides/mpa.en-US.md
Improve build speed by specifying which pages to start using the `MPA_FILTER` environment variable. This is useful for large projects where only a subset of pages needs to be built or served.
```text
# file .env
# Will only start bar, foo these two pages
MPA_FILTER=bar,foo
```
--------------------------------
### Icon Configuration Examples
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/max/layout-menu.en-US.md
Shows how to specify icons for menu items. Supports abbreviated line style icons and explicitly named filled or two-tone icons.
```typescript
// Line style
icon: 'home'; // Line style can be abbreviated
icon: 'HomeOutlined';
// Solid style
icon: 'HomeFilled';
// Two-tone style
icon: 'HomeTwoTone';
```
--------------------------------
### Install pnpm Package Manager
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/guides/getting-started.en-US.md
Install the pnpm package manager, which is recommended by the UmiJS team. Ensure you have a compatible version.
```bash
curl -fsSL https://get.pnpm.io/install.sh | sh -
pnpm -v
7.3.0
```
--------------------------------
### Install Umi Lint Module
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/guides/lint.md
Install the `@umijs/lint` package as a development dependency for Umi projects. For Umi Max, linting is built-in.
```bash
npm i @umijs/lint -D
# or
pnpm add @umijs/lint -D
```
--------------------------------
### 通过配置启用插件
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/guides/plugins.md
在 `config` 文件中通过 `presets` 和 `plugins` 配置插件,配置内容为插件的路径。内置插件通过对其 `key` 进行配置来启用。
```js
export default {
presets: ['./preset/foo','bar/presets'],
plugins: ['./plugin', require.resolve('plugin_foo')]
}
```
--------------------------------
### addPrepareBuildPlugins
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/api/plugin-api.en-US.md
Add plugins for build preparation.
```APIDOC
## addPrepareBuildPlugins
### Description
Add plugins for build preparation.
### Usage
```ts
api.addPrepareBuildPlugins(() => [
// return a plugin or array of plugins
])
```
```
--------------------------------
### Build Umi App for Production
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/api/commands.md
Use the `umi build` command to compile your project for production deployment. This command optimizes your code for performance and size.
```bash
umi build
```
--------------------------------
### Custom Valtio Extension Example: `proxyWithPersist`
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/max/valtio.en-US.md
An example of creating a custom Valtio extension function, `proxyWithPersist`, demonstrating composability and type safety.
```typescript
export function proxyWithPersist(val: V, opts: {
key: string;
}) {
const local = localStorage.getItem(opts.key);
const state = proxy(local ? JSON.parse(local) : val);
subscribe(state, () => {
localStorage.setItem(opts.key, JSON.stringify(snapshot(state)));
});
return state;
}
```
--------------------------------
### Extended Route Configuration Example
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/max/layout-menu.en-US.md
Demonstrates various configuration options for a route, including menu display, rendering of layout components, and permission settings. Use these properties to customize how a route appears and behaves within the layout.
```typescript
export const routes: IBestAFSRoute[] = [
{
path: '/welcome',
component: 'IndexPage',
name: 'Welcome', // This notation is compatible
icon: 'testicon',
// For more features see
// https://beta-pro.ant.design/docs/advanced-menu
// ---
// Open in a new page
target: '_blank',
// Don't show the top bar
headerRender: false,
// Don't show the footer
footerRender: false,
// Don't show the menu
menuRender: false,
// Don't show the menu header
menuHeaderRender: false,
// Permission configuration, needs to be used with the plugin-access
access: 'canRead',
// Hide submenu
hideChildrenInMenu: true,
// Hide self and submenu
hideInMenu: true,
// Hide in breadcrumb
hideInBreadcrumb: true,
// Sub-items up, still displayed,
flatMenu: true,
},
];
```
--------------------------------
### Create a New UmiJS Project
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/guides/boilerplate.md
Use this command to initialize a new UmiJS project. You can specify a folder name or let the wizard prompt you.
```bash
pnpm create umi
# In the current directory, create a project in the my-umi-app folder
pnpm create umi my-umi-app
```
--------------------------------
### Get Match Information for Path
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/api/api.en-US.md
Hook to get match information for a given path. Returns null if no match. Useful for extracting parameters from the URL.
```typescript
import { useMatch } from 'umi';
// when url = '/events/12'
const match = useMatch('/events/:eventId');
console.log(match?.pathname, match?.params.eventId);
// '/events/12 12'
```
--------------------------------
### Default Loader Implementation Example
Source: https://github.com/umijs/umi/blob/master/docs/docs/docs/max/micro-frontend.md
An example implementation of a default loader component that accepts a `loading` boolean prop and uses antd's Spin component.
```tsx
// defaultLoader.tsx
import { Spin } from 'antd';
export default function (loading: boolean) {
return ;
}
```