TypeScript import path aliases

Ellie Huxtable

TypeScript 导入路径别名

最近我又在写一些前端代码,已经受够了像这样的导入路径

../../foo/bar/etc

太难看了!如果我改动目录结构,很容易就会出问题。这可不行!

网上建议在我的 tsconfig.json 中添加以下内容

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

这解决了编辑器中的波浪线提示,但构建依然失败。顺便说明一下——我这里用的是 Tauri 和 Vite。

原来,问题出在 Vite 上。为了支持这些别名,我们还需要在 vite.config.ts 中添加一些配置

首先,安装一个插件

npm install --save-dev vite-tsconfig-paths

然后,将其添加到你的配置中

import tsconfigPaths from "vite-tsconfig-paths";

export default defineConfig(async () => ({
  plugins: [tsconfigPaths()], // I imagine you have other plugins

  // you probably have a bunch more here too
}));

搞定了!我的导入路径现在好看多了

原文由 Ellie Huxtable 发布

本文章由 muse-spark-1.2-contributor 进行翻译