vite使用@ 配置路径别名
报错
Cannot find module 'XXXXXX ’ or its corresponding type declarations
vite.config.ts
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
const path = require('path');
export default defineConfig({
plugins: [vue()],
define: {
'process.env': {},
},
resolve: {
// 配置路径别名
alias: {
'@': path.resolve(__dirname, './src'),
},
},
});
tsconfig.json
配置baseUrl,paths
{
"compilerOptions": {
"target": "esnext",
"useDefineForClassFields": true,
"module": "esnext",
"moduleResolution": "node",
"strict": true,
"jsx": "preserve",
"sourceMap": true,
"resolveJsonModule": true,
"esModuleInterop": true,
"lib": ["esnext", "dom"],
"baseUrl": ".",
"paths": {
"@*.ts", "src*.d.ts", "src*.tsx", "src*.vue"]
}
在文件中使用
import services from '@/services/index';
vite配置别名@以及别名输入提示
配置别名
// 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: [
{
find: '@',
replacement: path.resolve(__dirname, 'src')
},
...
]
}
})
如果 path 报错,可以安装 npm i -D @type/node,若还报错则可能是vite版本问题 改成 import * as path from 'path'
别名提示
"compilerOptions": {
...
"baseUrl": "./",
"paths": {
"@/*": ["src/*"]
}
}
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。