ReactJS - 在 jsconfig.json 中指定“路径”时找不到模块

New*_*der 8 reactjs

考虑 jsconfig.json 中的以下设置

{
    "compilerOptions": {
        "baseUrl": ".",
        "paths": {
            "@components/*": ["src/components/*"],
            "@constants/*": ["src/constants/*"]
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

app-constants.js当我尝试通过以下方式在组件中导入文件时:

import AppConstants from "@constants/app-constants";
Run Code Online (Sandbox Code Playgroud)

我似乎收到以下错误:

Module not found: Can't resolve '@constants/app-constants'
Run Code Online (Sandbox Code Playgroud)

我的app-constants.js文件直接位于src/constants文件夹中:

在此输入图像描述

知道为什么会发生这种情况吗?

编辑

我尝试使用这个:

{
  "compilerOptions": {
    "baseUrl": "src"
  },
  "include": ["src"]
}
Run Code Online (Sandbox Code Playgroud)

并且在直接调用文件夹时有效,例如constants/app-constants.js

但当我尝试第一种方法时却没有。

如果有人能够启发我纠正我的错误,那就太好了。

Sha*_*Gir 2

您的代码看起来不错,您可以通过智能感知来验证它,例如:

import AppConstants from "@constants/";
Run Code Online (Sandbox Code Playgroud)

它将显示app-constants智能感知中。

现在的问题是react还不支持aliases,但是很快就会支持。

我不知道我们是否会很快添加对别名的支持。我个人现在没有时间去做这件事。我认为当前选项将 baseUrl 设置为 . 或 src 足以解决相对进口的问题。除此之外,这只是个人喜好,例如使用 @ 而不是 src 作为前缀。

https://github.com/facebook/create-react-app/issues/7795