在Vite+TypeScript的项目中使用~和@代替src根路径的方法

原由

当前端项目组件比较多的时候,引用组件会面临路径特别长的情况,不易维护且容易出错。定义绝对路径映射是个好办法,下面就介绍 Vite+TypeScript 的项目中中的具体实现。

方案

  • vite.config.ts

    1
    2
    3
    4
    5
    resolve: {
    alias: {
    "~": path.resolve(path.dirname(fileURLToPath(import.meta.url)), "src"),
    }
    }
  • tsconfig.json

    1
    2
    3
    4
    5
    6
    {
    "compilerOptions": {
    "paths": {
    "~/*": ["./src/*"]
    }
    }

使用

1
2
3
4
5
6
import {API_TYPE_CONSTANTS} from "~/utils/constants/apiTypeConstants";
import MetaweblogMain from "~/components/publish/tab/main/MetaweblogMain.vue";

// 原来的
// import {API_TYPE_CONSTANTS} from "../../../../../../utils/constants/apiTypeConstants";
// import MetaweblogMain from "../../MetaweblogMain.vue";

在Vite+TypeScript的项目中使用~和@代替src根路径的方法

https://hexo.terwer.space/post/in-the-project-of-vite-typescript-replace-src-root-path-5ox0i.html

作者

Terwer

发布于

2022-11-22

更新于

2022-11-22

许可协议

评论