Raf*_*aeu 7 typescript create-react-app
我试图通过将以下值添加到tsconfig.json中来设置项目中的Path别名:
"compilerOptions": {
"baseUrl": "src",
"paths": {
"@store/*": ["store/*"]
},
Run Code Online (Sandbox Code Playgroud)
如果我创建导入,则IntelliJ或VSCode都不会打扰我:
import { AppState } from '@store/index';
Run Code Online (Sandbox Code Playgroud)
但是,当我编译应用程序时,会收到以下警告:
The following changes are being made to your tsconfig.json file:
- compilerOptions.paths must not be set (aliased imports are not supported)
Run Code Online (Sandbox Code Playgroud)
它炸弹说找不到参考:
TypeScript error in C:/xyz.tsx(2,26):
Cannot find module '/store'. TS2307
Run Code Online (Sandbox Code Playgroud)
有任何解决方法或不支持的解决方法create-react-app --typescript?
Ива*_*лев 19
就我而言,我使用craco和craco-alias解决了这个问题
安装craco和craco-alias npm install @craco/craco --save和npm i -D craco-alias
tsconfig.paths.json在根目录下创建
{
"compilerOptions": {
"baseUrl": "./src",
"paths": {
"@components/*" : ["./components/*"]
}
}
}
Run Code Online (Sandbox Code Playgroud)
扩展tsconfig.paths.json在tsconfig.json
{
"extends": "./tsconfig.paths.json",
//default configs...
}
Run Code Online (Sandbox Code Playgroud)
创建craco.config.js根猪病
const CracoAlias = require("craco-alias");
module.exports = {
plugins: [
{
plugin: CracoAlias,
options: {
source: "tsconfig",
// baseUrl SHOULD be specified
// plugin does not take it from tsconfig
baseUrl: "./src",
/* tsConfigPath should point to the file where "baseUrl" and "paths"
are specified*/
tsConfigPath: "./tsconfig.paths.json"
}
}
]
};
Run Code Online (Sandbox Code Playgroud)
在package.json交换"start": "react-scripts start"与"start": "craco start"
Abr*_*ham 13
您可以这样做,直接导入相对于src目录的文件
转到您的tsconfig.json文件添加基本 URL"."
"compilerOptions": {
"baseUrl":".",
...
Run Code Online (Sandbox Code Playgroud)
src然后你可以直接从目录导入东西
import Myfile from "src/myfile.js"
Run Code Online (Sandbox Code Playgroud)
okl*_*las 10
该解决方案是反应-APP-再布线别名(对于反应-APP-重新布线或定制-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)
}
Run Code Online (Sandbox Code Playgroud)
像这样在 json 中配置别名:
// tsconfig.paths.json
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"example/*": ["example/src/*"],
"@library/*": ["library/src/*"]
}
}
}
Run Code Online (Sandbox Code Playgroud)
并在extends主打字稿配置文件的部分添加此文件:
// tsconfig.json
{
"extends": "./tsconfig.paths.json",
// ...
}
Run Code Online (Sandbox Code Playgroud)
使用 create-reat-app 4.0 和 typescript 导入文件 NearSrc.tsx 在 src 之外的工作示例演示工作解决方案在这里
编辑 - 20/3/20 - 以上答案有一个带有插件的解决方案。
有同样的问题。在发布时,它目前不受支持。
此功能仍在与 CRA 团队一起开发:https : //github.com/facebook/create-react-app/pull/6116
如果您编辑 tsconfig CRA 会删除更改:https : //github.com/facebook/create-react-app/issues/6269
此线程中有一些技巧:https : //github.com/facebook/create-react-app/issues/5118可以使别名正常工作,但是需要自定义不适合我的用例的 CRA 设置(使用 CRA照原样)。
| 归档时间: |
|
| 查看次数: |
896 次 |
| 最近记录: |