[英]React Native absolute paths don't seem to work
I try to configure React Native to use absolute paths to ease the imports pain.我尝试将 React Native 配置为使用绝对路径来缓解导入的痛苦。 I tried various methods and nothing seem to work for me.我尝试了各种方法,但似乎没有什么对我有用。 There's my tsconfig.json:这是我的 tsconfig.json:
{
"compilerOptions": {
"allowJs": true,
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"isolatedModules": true,
"jsx": "react",
"lib": ["es6"],
"moduleResolution": "node",
"noEmit": true,
"strict": true,
"target": "esnext",
"baseUrl": "src"
},
"include": ["src"],
"exclude": [ "node_modules", "babel.config.js", "metro.config.js"]
}
And babel.config.js:和 babel.config.js:
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
plugins: [['module-resolver', { root: ['./src'] }]],
}
I tried with, or without babel plugin.我尝试使用或不使用 babel 插件。 Tried different configurations I found googling.尝试了不同的配置,我发现谷歌搜索。 I tried adding "baseUrl": "src"
without paths option, or "baseUrl": "./src"
.我尝试添加"baseUrl": "src"
without paths 选项,或"baseUrl": "./src"
。 I tried different variations of "paths": {"*": ["./src/*"]}
, "paths": {"*": ["src/*"]}
and so on.我尝试了"paths": {"*": ["./src/*"]}
、 "paths": {"*": ["src/*"]}
等的不同变体。 I tried adding "include": ["src"]
or removing it.我尝试添加"include": ["src"]
或删除它。 VS Code understands imports very well, but when I run the app, it will crash on absolute paths. VS Code 非常了解导入,但是当我运行应用程序时,它会在绝对路径上崩溃。 Is there anything obvious I'm missing?有什么明显的我失踪了吗?
Try adding a jsconfig.json
in your root folder like:尝试在根文件夹中添加jsconfig.json
,例如:
{
"compilerOptions": {
"baseUrl": "src"
},
"include": ["src"]
}
If you are using TS you can configure the baseUrl
setting inside the compilerOptions
of your project's tsconfig.json
file.如果您使用的是 TS,您可以在项目的tsconfig.json
文件的compilerOptions
中配置baseUrl
设置。
So now, if your src
folder contains a components
one, you can do:所以现在,如果您的src
文件夹包含一个components
,您可以执行以下操作:
import MyComponent from 'components/MyComponent';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.