场景说明
ReactNative项目,并且用的是TypeScript模板构建(npx react-native init rn_demo --template react-native-template-typescript
),并且项目中的rn代码都存放在 react 目录中
配置
- 安装路径解析的babel插件(babel-plugin-module-resolver)
npm install --save-dev babel-plugin-module-resolver
- 配置
tsconfig.json
中的paths
,需要将baseUrl设置成相对路径
{
"extends": "@tsconfig/react-native/tsconfig.json", /* Recommended React Native TSConfig base */
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
/* Completeness */
"skipLibCheck": true, /* Skip type checking all .d.ts files. */
/* 配置基础地址 */
"baseUrl": ".",
/* 配置路径别名 */
"paths": {
"*": ["react/*"],
}
}
}
3.配置 babel.config.js
,将module-resolver
加入到plugins
中,同时设置alias
和tsconfig.json
的paths
保持一致
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
plugins: [
[
'module-resolver',
{
root: ['./react'],
extensions: ['.ios.js', '.android.js', '.js', '.ts', '.tsx', '.json'],
alias: {
'*': ['./react'],
},
},
],
],
};
使用
在项目中可以直接使用xxx/xxx
直接访问react
目录下的文件(不需要带react
目录)