尝试导入 ts 文件时路径别名 vite 出错

Gia*_*vez 6 typescript vuejs3 vite

使用 vite 中的路径别名导入 ts 文件时出错,如果导入组件(.vue)文件,则没有问题,但如果尝试导入 ts,则会出现此错误

使用 vite 的路径别名导入 ts 文件时出错

Vite 别名的默认配置

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

export default defineConfig({
    plugins: [vue()],
    resolve: {
        alias: {
            '@/': new URL('./src/', import.meta.url).pathname,
        },
    },
})
Run Code Online (Sandbox Code Playgroud)

Gia*_*vez 14

我必须添加这个

"paths": {
    "@/*": [
        "./src/*"
    ],
},
Run Code Online (Sandbox Code Playgroud)

在属性内的 tsconfig.json 文件上compilerOptions。所以,我的 tsconfig.json 看起来像这样

{
  "compilerOptions": {
    "target": "ESNext",
    "useDefineForClassFields": true,
    "module": "ESNext",
    "moduleResolution": "Node",
    "strict": true,
    "jsx": "preserve",
    "sourceMap": true,
    "resolveJsonModule": true,
    "isolatedModules": true,
    "esModuleInterop": true,
    "lib": ["ESNext", "DOM"],
    "skipLibCheck": true,
    "paths": {
        "@/*": [
            "./src/*"
        ],
    },
  },
  "include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"],
  "references": [{ "path": "./tsconfig.node.json" }]
}

Run Code Online (Sandbox Code Playgroud)