我尝试将 React Native 配置为使用绝对路径来减轻导入的痛苦。我尝试了各种方法,但似乎没有什么对我有用。这是我的 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"]
}
还有 babel.config.js:
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
plugins: [['module-resolver', { root: ['./src'] }]],
}
我尝试使用或不使用 babel 插件。尝试了不同的配置,我发现谷歌搜索。我尝试添加不带路径选项的 "baseUrl": "src"
或 "baseUrl": "./src"
。我尝试了 "paths": {"*": ["./src/*"]}
、"paths": {"*": ["src/*"]}
等的不同变体。我尝试添加 "include": ["src"]
或删除它。 VS Code 非常理解导入,但是当我运行该应用程序时,它会在绝对路径上崩溃。有什么明显的我遗漏了吗?
答案 0 :(得分:0)
尝试在您的根文件夹中添加一个 jsconfig.json
,例如:
{
"compilerOptions": {
"baseUrl": "src"
},
"include": ["src"]
}
如果您使用的是 TS,您可以在项目的 baseUrl
文件的 compilerOptions
中配置 tsconfig.json
设置。
现在,如果您的 src
文件夹包含一个 components
,您可以:
import MyComponent from 'components/MyComponent';