我试图通过将这些值添加到 tsconfig.json 来在我的项目中设置路径别名:
"compilerOptions": {
"baseUrl": "src",
"paths": {
"@store/*": ["store/*"]
},
如果我创建一个导入,IntelliJ 或 VSCode 都不会打扰我:
import { AppState } from '@store/index';
但是当我编译应用程序时,我收到了这个警告:
The following changes are being made to your tsconfig.json file:
- compilerOptions.paths must not be set (aliased imports are not supported)
它轰炸说它找不到引用:
TypeScript error in C:/xyz.tsx(2,26):
Cannot find module '/store'. TS2307
是否有任何解决方法或不受
create-react-app --typescript
支持?
最佳答案
解决方法是 react-app-rewire-alias (对于 react-app-rewired 或 customize-cra 或 craco ):
根据文档替换 react-scripts
在 package.json
并配置下一步:
// config-overrides.js
const {alias, configPaths} = require('react-app-rewire-alias')
module.exports = function override(config) {
return alias(configPaths('./tsconfig.paths.json'))(config)
}
像这样在 json 中配置别名:// tsconfig.paths.json
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"example/*": ["example/src/*"],
"@library/*": ["library/src/*"]
}
}
}
并将此文件添加到 extends
主要 typescript 配置文件的部分:// tsconfig.json
{
"extends": "./tsconfig.paths.json",
// ...
}
使用 create-reat-app 4.0 和 typescript 导入文件 NearSrc.tsx 在 src 之外的工作示例演示工作解决方案是 here
关于typescript - create-react-app Typescript 3.5,路径别名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57070052/