配置vite path alias

886 阅读1分钟

vue项目里经常会遇到import PageA from "@/test/PageA.vue"这种路径写法,为的是当路径层级变得比较深时,不会写起来太乱,找起来麻烦。

vite.config.ts

vite.config.ts里添加path alias,向vite说明这样子的路径怎么去解析出最终完整的路径。

export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      "@": path.resolve(__dirname, "./src")
    }
  }
})

最简单的一份配置:@是绑定到项目的src路径下。可以继续添加更多的路径别名。

tsconfig.json

另外在vscode里使用volar插件,它会在编写vue代码时提供很多有用的帮助,光上面那样子配置vite.config.ts,并不会告诉volar在分析这些路径时到底应该怎么解析。还要在 tsconfig.json 里添加如下配置:

compilerOptions: {
    "baseUrl": "./",
    "paths": {
          "@/*": [
            "src/*"
          ]
    }
}

这样volar才不会报类似的错:Cannot find module '@/utils/index' or its corresponding type declarations.

如果不在tsconfig.json里配置paths,其实并不影响代码的正常运行,vite已经知道怎么解析路径了。只是volar不知道怎么解析,导致代码提示出现问题。