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

提问:在Create React App中配置带@前缀的绝对导入如何实现?

在Create React App中配置带@前缀的绝对导入

你只需要在tsconfig.json的compilerOptions里新增paths配置,把带@前缀的路径映射到src目录下对应的文件夹即可,具体操作如下:

  1. 更新tsconfig.json配置
    在已有的baseUrl基础上,添加paths字段,指定@前缀的路径映射规则:
{
  "compilerOptions": {
    "baseUrl": "src",
    "paths": {
      "@components/*": ["components/*"],
      // 若还有其他需要用@前缀的目录,可以继续追加,比如:
      // "@utils/*": ["utils/*"],
      // "@styles/*": ["styles/*"]
    }
  },
  "include": ["src"]
}
  1. 适配ESLint(如果项目用到)
    如果你的项目配置了ESLint,可能会出现路径无法识别的报错,需要在ESLint配置文件(比如.eslintrc.js)中添加解析器配置:
module.exports = {
  // ...其他已有配置
  settings: {
    'import/resolver': {
      typescript: {
        project: './tsconfig.json'
      }
    }
  }
}
  1. 重启编辑器
    修改完配置后,重启你的代码编辑器(比如VS Code),让新配置生效,之后就可以使用import MyComponent from "@components/MyComponent"这类带@前缀的导入方式了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 07:18:21