问题描述
我正在尝试映射tsconfig.json中的路径以摆脱相对路径。我的React App基于Create-React-App。 我尝试了此SO thread,并在tsconfig.json中添加了路径。我的tsconfig.json是
{
"compilerOptions": {
"baseUrl": "src","target": "es5","lib": [
"dom","dom.iterable","esnext"
],"allowJs": true,"skipLibCheck": true,"esModuleInterop": true,"allowSyntheticDefaultImports": true,"strict": true,"forceConsistentCasingInFileNames": true,"module": "esnext","moduleResolution": "node","resolveJsonModule": true,"isolatedModules": true,"noEmit": true,"jsx": "react","strictnullchecks": false
},"include": [
"src"
]
}
当我在VS Code中编译项目时,它会从tsconfig.json中删除路径条目,并显示以下消息。为什么我的基于React脚本的React Project不支持别名导入?
解决方法
您必须将 "baseUrl": ".",
添加到编译器选项中,然后才能直接使用导入 src/your/path
。
您可能已经想通了,但在我们等待 pull request that adds this to tsconfig 目前与 create-react-app react v 17.0.2 有同样的问题,
我在 gatsby 应用程序中遇到了类似的问题,您无法在不更改 web 包配置的情况下设置别名导入
this thread 对 cra without 打字稿中的别名导入有很好的解释,但最终应该会导致相同的配置。
你必须要么eject(除非你有其他问题需要在你的 webpack 配置中解决,否则不要这样做。)或者使用另一个包,比如 CRACO 或 {{3 }} 通过 webpack 配置你的别名。
React-App-Rewired 很可能是您要查找的内容。
安装 This Stackoverflow answer 然后创建 config-overrides.js 并将此代码放在那里 ->
//config-overrides.js
const { alias,configPaths } = require('react-app-rewire-alias');
module.exports = function override(config) {
return alias(configPaths('./tsconfig.paths.json'))(config);
};
在 tsconfig.paths.json 中创建你的路径对象
//tsconfig.paths.json
{
"compilerOptions": {
"baseUrl": "./src","paths": {
"@components": ["components"],"@styles": ["styles"],"@config": ["config"]
}
}
}
然后在 tsconfig 内部扩展这些选项(而不是在 compilerOptions 内部)
//tsconfig.js
"extends": "./tsconfig.paths.json"
最后,用 react-app-rewired 替换 package.json 中的每个 react-scripts 脚本
//package.json
"scripts": {
"start": "react-app-rewired start","build": "react-app-rewired build","test": "react-app-rewired test","eject": "react-app-rewired eject"
},
你应该准备好去追求这个。 希望这可以帮助其他任何在 create-react-app 中遇到此问题的人。