首页 > 解决方案 > 如何在反应中为所有导入设置基本路径

问题描述

在 create-react-app cli 项目中,使用下面的配置将所有导入路径设置src为基本 url

jsconfig.json

{
  "compilerOptions": {
    "jsx": "react",
    "baseUrl": "src/",
    "paths": {
      "~/*": ["./*"]
    }
  }
}

包.json

..
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts --max_old_space_size=4096 build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },

我想使用这样的导入语句:

import { PanelHeader } from '@/components/panel';

而不是这个:

import { PanelHeader } from '../../../components/panel';

标签: reactjsvisual-studio-code

解决方案


通过检查CRA 上的Absolute Imports,您可以看到两件事:

(1) 设置baseUrlsrc

{
  "compilerOptions": {
    "baseUrl": "src"
  },
  "include": ["src"]
}

(2)从名为(文件夹的子文件夹)的文件夹中components/..导入组件时使用componentssrc

例子 -import Button from 'components/Button';

所以,去掉@/一部分。


推荐阅读