基本配置
需要加入path
依赖:
npm install path
在 vite.config.ts 文件的配置:
import { defineConfig } from "vite"
import react from "@vitejs/plugin-react"
import path from "path"
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
resolve: {
alias: {
"@": path.resolve(__dirname, "./src")
}
}
})
在 typescript 项目中进行配置
在 vite + typescript 中配置路径别名时需要注意, 直接使用__dirname
的话, typescript 会报错cannot find name '__dirname'
, 这时候需要拉取依赖
npm install -D @types/node
来给让 typescript 识别出__dirname
.
并且需要在ts.config.json
内设置:
"compilerOptions":{
"paths":{
"@/*": ["./src/*"],
},
}
注意, 若在src
前无./
, 可能会报错:
Non-relative paths are not allowed when 'baseUrl' is not set. Did you forget a leading './'?
这是因为需要在ts.config.json
中指定相对路径, 只需要指定相对路径即可.
# 同级目录下的相对路径
./
# 上级目录下的相对路径
../
使用 vscode 时无 intelligence(智能提示)
需要在ts.config.json
或者jsconfig.json
中设置:
"compilerOptions":{
"baseUrl":"./"
}
来指定项目的基本路径. 这时候在 vscode 中路径引入时打出@
之后, 就可以提示路径了.
设置baseUrl
后, 可以不用在paths
配置内使用相对路径了.
reference
- https://bobbyhadz.com/blog/typescript-cannot-find-name-dirname