在 React 和 Typescript 中,为什么我的绝对路径不适用于嵌套文件夹?

问题描述 投票:0回答:2

我正在尝试在我的 React 项目中设置绝对路径,但在嵌套文件夹和使用

@
前缀时遇到了一些问题。

在我的

tsconfig.json
中进行以下设置:

{
  "compilerOptions":{
    "baseUrl":"src",
    "paths":{
      "global/*":[
        "./global/*"
      ],
      "features/*":[
        "./features/*"
      ],
      "content/*":[
        "./features/content/*"
      ]
    }
  },
  "include":[
    "src"
  ]
}

这有效:

import "features/content/css/viewContent.css";

但这并不:

import "content/css/viewContent.css";

我在使用

@
前缀时也遇到问题,例如在我的
tsconfig.json
中使用以下设置:

{
  "compilerOptions":{
    "baseUrl":"src",
    "paths":{
      "global/*":[
        "./global/*"
      ]
    }
  },
  "include":[
    "src"
  ]
}

这有效:

import "global/components/example";

但是在我的设置中添加

@
前缀就像这样:

{
  "compilerOptions":{
    "baseUrl":"src",
    "paths":{
      "@global/*":[
        "./global/*"
      ]
    }
  },
  "include":[
    "src"
  ]
}

不起作用:

import "@global/components/example";

以上示例的文件结构如下:

└── root dir
    ├── src
    │   └── features
    │       ├── content
    │           └── css
    │           └── etc...
    │           └── etc...
    │           └── etc...
    │   └── global
    │       ├── components 
    │       └── etc...
    │       └── etc...
    │       └── etc...
    │  
    └── tsconfig.json 

我也按照步骤操作 这里但不幸的是没有太多运气。

任何帮助将不胜感激。

reactjs typescript absolute-path
2个回答
1
投票

这取决于您用来运行应用程序的服务器。

我对 Vite 有同样的问题,实际上有一个为此制作的库:vite-tsconfig-paths

但我不喜欢为像这样的小问题导入库。


0
投票

这原来是使用 create-react-app 引起的问题。我设法通过使用 craco 并将路径添加到我的

craco.config.js
来解决这个问题(以及将它们放在我的
tsconfig.json
文件中)

craco.config.js

const path = require("path");

module.exports = {
  webpack: {
    alias: {    
      "@global": path.resolve(__dirname, "src/global/"),
      // etc...     
    },
  },
};

tsconfig.json

"compilerOptions": {
  // etc...
  "baseUrl": "src",
  "paths": {
    "@global/*": ["./global/*"],
  }
// etc...
© www.soinside.com 2019 - 2024. All rights reserved.