如何在前端 React 项目中使用 tsconfig 路径别名

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

我想在我的 create-react-app React 前端项目中设置路径配置

mylib

这是我的

tsconfig.json

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

这是我的项目文件夹的外观:

mylib
-build
-src
--stuff
---things
----x.js

这个项目是我使用 Babel 编译的自定义库,并且我

npm link
在另一个 React 项目
myproject
中测试它。 这是
myFile.tsx
myproject
文件的顶部:

import * as myImport from '@bla/stuff/things/x'

这是输出:

编译失败。 ../myproject/build/stuff/things/myFile.js 找不到模块:无法解析“@bla/stuff/things/x” 'C:\Users\xxx\myproject uild oldInWhichMyFileIs'

我在这里缺少什么?

我发现了其他相关的SO问题,但人们说使用

module-alias
库,它仅适用于后端代码。我也不用
ts-node

reactjs typescript create-react-app tsconfig
1个回答
0
投票

您通常会设置路径别名来简化导入。这可以使您的项目的目录结构更清晰且更易于管理。

tsconfig
必须在项目根目录下,然后你可以使用这样的文件夹结构,如果文件夹有子文件夹你需要包含它

// This does't work ❌
{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
     //...
    "baseUrl": ".",
  },
  "include": ["next-env.d.ts", "twin.d.ts", "**/*.ts", "**/*.tsx"],
  "exclude": ["node_modules"],
  "paths": {
      "@components/*": ["components/*"],
      "@lib/*": ["lib/*"]
    }
}
// This should work ✅
{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
     //...
    "baseUrl": ".",
    "paths": {
      "@components/*": ["components/*"],
      "@lib/*": ["lib/*"]
    }
  },
  "include": ["next-env.d.ts", "twin.d.ts", "**/*.ts", "**/*.tsx"],
  "exclude": ["node_modules"],
}
© www.soinside.com 2019 - 2024. All rights reserved.