配置 @ 路径别名

Siona

Vue3 + TypeScript 配置 @ 路径别名

Vue3 + TypeScript + Vite 配置 @ 路径别名

1. 安装 path 依赖

npm i @types/node -D
# or
yarn add @types/node -D
yarn add @types/node --dev
// package.json
{
    "devDependencies": {
        "@types/node": "^20.11.24",
        "@vitejs/plugin-vue": "^5.0.4",
        "typescript": "^5.2.2",
        "vite": "^5.1.4",
        "vue-tsc": "^1.8.27"
    }
}

2. 修改 vite.config.ts

import {defineConfig} from 'vite'
import vue from '@vitejs/plugin-vue'
import {resolve} from 'path'

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

自动导入 path 会报错,Vue: Cannot find module path or its corresponding type declarations. 。 可直接复制上述代码。

3. 修改 tsconfig.json

在 tsconfig.json 文件中,配置 baseUrlpaths

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

tsconfig.json 完整代码

// tsconfig.json
{
    "compilerOptions": {
        "target": "ES2020",
        "useDefineForClassFields": true,
        "module": "ESNext",
        "lib": [
            "ES2020",
            "DOM",
            "DOM.Iterable"
        ],
        "skipLibCheck": true,

        /* Project Setting */
        /* 配置 @ 路径 */
        "baseUrl": "./",
        "paths": {
            "@/*": [
                "src/*"
            ]
        },

        /* Bundler mode */
        "moduleResolution": "bundler",
        "allowImportingTsExtensions": true,
        "resolveJsonModule": true,
        "isolatedModules": true,
        "noEmit": true,
        "jsx": "preserve",

        /* Linting */
        "strict": false,
        "noUnusedLocals": false,
        "noUnusedParameters": false,
        "noFallthroughCasesInSwitch": false
    },
    "include": [
        "src/**/*.ts",
        "src/**/*.tsx",
        "src/**/*.vue"
    ],
    "references": [
        {
            "path": "./tsconfig.node.json"
        }
    ]
}
Last Updated 3/6/2024, 10:02:39 AM