如何在基于TypeScript的React Native应用程序中为导入配置绝对路径? [英] How do I configure absolute paths for imports in TypeScript based React Native apps?
本文介绍了如何在基于TypeScript的React Native应用程序中为导入配置绝对路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为了避免在基于TypeScript的React Native应用程序中使用'../../../../'样式的相对导入,我想对应用程序进行配置,以便可以使用绝对导入.
In order to avoid '../../../../' style relative imports in a TypeScript based React Native app, I would like to configure the app so that I can use absolute imports instead.
此配置还必须支持Jest单元测试,这一点很重要.
It is important that the configuration also supports Jest unit tests.
我使用npx react-native init MyTestApp --template typescript
原生版本:0.60.5
React Native version: 0.60.5
要实现这一目标,我需要什么确切的配置?
What is the exact configuration I would need to achieve this?
推荐答案
要求
// Meh
import config from '../../../../../../../config';
// Awesome!
import config from '@cuteapp/config';
操作方法
- 添加此babel插件包
yarn add --dev babel-plugin-module-resolver
- 我的
babel.config.js
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
plugins: [
[
'module-resolver',
{
cwd: 'babelrc',
extensions: ['.ts', '.tsx', '.js', '.ios.js', '.android.js'],
alias: {
'@cuteapp': './app'
}
}
],
'jest-hoist'
]
};
- 我的
tsconfig.json
{
"compilerOptions": {
"allowJs": true,
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"isolatedModules": true,
"jsx": "react",
"lib": ["es2015", "es2015.promise", "es2016.array.include", "dom"],
"strict": true,
"moduleResolution": "node",
"baseUrl": "./",
"paths": {
"@cuteapp/*": ["app/*/index", "app/*"]
},
"noEmit": true,
"resolveJsonModule": true,
"target": "esnext",
"types": ["jest"]
},
"exclude": ["node_modules", "babel.config.js", "metro.config.js"]
}
- 就是这样.
这篇关于如何在基于TypeScript的React Native应用程序中为导入配置绝对路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文