vite vue-ts 配置 “@” 路径别名

16,099 阅读1分钟

序章、版本

"@types/node": "^16.9.1"
"vite": "^2.5.4"
"@vitejs/plugin-vue": "^1.6.1"
"@vue/compiler-sfc": "^3.2.6"
"vue-tsc": "^0.2.2"
"typescript": "^4.3.2"

只要实现了,没有报错,版本不一样也无所谓

一、安装依赖

npm i @types/node -D

二、修改vite.config.js

import { defineConfig } from 'vite'
import { resolve } from 'path'

export default defineConfig {
    // ...
    resolve: {
        alias: {
            "@": resolve(__dirname, 'src'), // 路径别名
        },
        extensions: ['.js', '.json', '.ts'] // 使用路径别名时想要省略的后缀名,可以自己 增减
    }
    // ...
}

vite 官方文档中 不建议忽略 .vue 后缀的文,所以在 import 引入文件的时候需要加 .vue cn.vitejs.dev/config/#res…

import HelloWorld from '@/components/HelloWorld.vue'

三、修改tsconfig.json

{
    "compilerOptions" : {
        // ...
        "baseUrl": ".", // 用于设置解析非相对模块名称的基本目录,相对模块不会受到baseUrl的影响
        "paths": { // 用于设置模块名到基于baseUrl的路径映射
            "@/*": ["src/*"]
        }
        // ...
    }
}