You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Vite中配置无@符号的基础绝对路径?

解决Vite中无@符号的绝对路径配置问题

你的配置存在两个核心错误:

  1. Alias路径多了多余的/*:path.resolve需要指向目录本身,带通配符会导致Vite无法正确解析别名映射。
  2. 缺少编辑器/语言服务的路径配置:仅配置Vite无法让VSCode等编辑器识别这些路径,会出现语法报错。

正确配置步骤

1. 修正Vite配置文件

去掉每个alias路径后的/*,确保指向目录本身:

import react from "@vitejs/plugin-react";
import { defineConfig } from "vite";
import path from "path";

export default defineConfig({
  base: "/",
  plugins: [react()],
  resolve: {
    alias: {
      "api": path.resolve(__dirname, "./src/api"),
      "context": path.resolve(__dirname, "./src/context"),
      "components": path.resolve(__dirname, "./src/components"),
    },
  },
  server: {
    port: 3000,
  },
});

2. 配置编辑器路径识别

在项目根目录创建jsconfig.json(JS项目)或tsconfig.json(TS项目),添加paths映射让编辑器识别这些绝对路径:

JS项目(jsconfig.json):

{
  "compilerOptions": {
    "baseUrl": "./src",
    "paths": {
      "api/*": ["api/*"],
      "context/*": ["context/*"],
      "components/*": ["components/*"]
    }
  },
  "include": ["src/**/*"]
}

TS项目(tsconfig.json):

{
  "compilerOptions": {
    "target": "ESNext",
    "useDefineForClassFields": true,
    "lib": ["DOM", "DOM.Iterable", "ESNext"],
    "allowJs": false,
    "skipLibCheck": true,
    "esModuleInterop": false,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "ESNext",
    "moduleResolution": "Node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx",
    "baseUrl": "./src",
    "paths": {
      "api/*": ["api/*"],
      "context/*": ["context/*"],
      "components/*": ["components/*"]
    }
  },
  "include": ["src"],
  "references": [{ "path": "./tsconfig.node.json" }]
}

效果验证

配置完成后,你就可以直接使用无@符号的绝对路径导入模块:

import Button from "components/General/Button";
import { fetchUser } from "api/user";

内容的提问来源于stack exchange,提问作者Tapialj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 17:07:02