引言
項目中的結(jié)構(gòu)比較固定的唐瀑,而通常在實際的開發(fā)中赠尾,會大量的涉及到使用import語法寸宵,一般都是會采用@路徑別名的方式,去進行定位文件夾赶掖,那么在vue3+ts+vite+vscode的環(huán)境下如何設(shè)置呈驶?
vite中路徑別名設(shè)置
注意配置項下的resolve下的alias就是進行相應(yīng)的設(shè)置。
// vite.config.ts
import type { UserConfig, ConfigEnv } from 'vite';
import { loadEnv } from 'vite';
import path from 'path';
export default ({ command, mode }: ConfigEnv): UserConfig => {
const root = process.cwd();
const env = loadEnv(mode, root);
// The boolean type read by loadEnv is a string. This function can be converted to boolean type
const viteEnv = wrapperEnv(env);
const { VITE_PORT, VITE_PUBLIC_PATH, VITE_PROXY, VITE_DROP_CONSOLE } = viteEnv;
const isBuild = command === 'build';
return {
base: VITE_PUBLIC_PATH,
root,
resolve: {
alias: {
'@': path.join(__dirname, './src'),
'@components': path.join(__dirname, './src/components'),
'@utils': path.join(__dirname, './src/utils'),
'@router': path.join(__dirname, './src/router'),
'@request': path.join(__dirname, './src/utils/request'),
'@store': path.join(__dirname, './src/store'),
'@storage': path.join(__dirname, './src/utils/storage'),
'@model': path.join(__dirname, './src/utils/model'),
'@service': path.join(__dirname, './src/api/service'),
'@handler': path.join(__dirname, './src/api/handler'),
},
},
...
}
tsconfig中的配置
進行了vite的配置后牺堰,vite是可以進行正確的路徑解析,但是進行點擊.vue文件跳轉(zhuǎn)時,跳轉(zhuǎn)進入的是vue定義的模塊
1.png
2.png
需要在tsconfig下的path配置項中進行處理:
// tsconfig.json
{
"compilerOptions": {
...
"paths": {
"@/*": ["src/*"],
"@model/*": ["src/api/model/*"],
"@service/*": ["src/api/service/*"],
"@handler/*": ["src/api/handler/*"],
"@types/*": ["types/*"],
"@utils/*": ["src/utils/*"],
"@router/*": ["src/router/*"],
"@store/*": ["src/store/*"],
"@components/*": ["src/components/*"],
"@request": ["src/utils/request"],
"@router": ["src/router"],
"@store": ["src/store"],
"@storage": ["src/utils/storage"]
}
},
...
}
帶有 /* 這種指的是文件夾 不帶的可以直接定位到文件的孔飒,比如 @router router不是文件艰争,但是它下面有index.ts逾柿,因此跳轉(zhuǎn)的是router/index.ts缀棍。
配置完成后爬范,就可以成功實現(xiàn)跳轉(zhuǎn):
3.png