使用 Vite 为 React 配置 Alias
Haiya Lv3

Vite 创建的 React 配置 Alias,以便能够使用@作为路径导入模块

安装依赖

Vite 创建的 React 项目,通常情况下没有安装 @types/node,会导致 import path 报错

1
npm install @types/node --save-dev

修改 vite.config.ts

添加 resolve 部分

1
2
3
4
5
6
7
8
9
10
11
12
13
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import path from "path";

// https://vite.dev/config/
export default defineConfig({
plugins: [react()],
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
},
},
});

修改 tsconfig.app.json

compilerOptions 中添加 Path mapping 部分

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
{
"compilerOptions": {
/* ...原始内容... */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true,
/* ...原始内容... */

/* Path mapping */
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
}
},
"include": ["src"]
}

配置完成后,即可使用 @ 作为路径导入依赖

1
import { MyUtil } from '@/utils/my-util'
由 Hexo 驱动 & 主题 Keep