ReactNative 配置路径别名
1、安装依赖 babel-plugin-module-resolver
yarn add babel-plugin-module-resolver -D
2、配置 babel.config.js
module.exports = { presets: ['module:metro-react-native-babel-preset'], plugins: [ [ '@babel/plugin-proposal-decorators', { legacy: true, }, ], // 配置 babel-plugin-module-resolver [ require.resolve('babel-plugin-module-resolver'), { root: ['.'], alias: { '*': ['./src'], assets: './src/assets', components: './src/components', modules: './src/modules', stores: './src/stores', utils: './src/utils', }, }, ], ], };
3、配置 tsconfig.json
{ "extends": "@tsconfig/react-native/tsconfig.json", "compilerOptions": { "experimentalDecorators": true /* Enables experimental support for ES7 decorators. */, "baseUrl": ".", // 配置基础地址 "paths": { "*": ["src/*"], "assets": ["src/assets"], "components": ["src/components"], "modules": ["src/modules"], "stores": ["src/stores"], "utils": ["src/utils"] } } }
4、运行 RN 项目,建议运行指令 yarn start --reset-cache 清除缓存后再启动对应的 iOS 或 Android 项目
5、在项目中使用路径别名引用对应的文件,如下图所示