安装 babel
yarn add babel-plugin-module-resolver
配置 babel.config.js 文件
文件会自动在根目录生成
配置如下
module.exports = {presets: ['module:metro-react-native-babel-preset'],
plugins: [
[
'module-resolver',
{root: ['./src'], // 表示哪个目录开始设置绝对路径
alias: {
// 别名的配置
'@/utils': './src/utils',
'@/pages': './src/pages',
'@/navigator': './src/navigator',
'@/models': './src/models',
'@/config': './src/config',
'@/components': './src/components',
'@/assets': './src/assets',
},
},
],
],
};
tsconfig.json 配置
"baseUrl": "./src" /* Base directory to resolve non-absolute module names. */,
"paths": {"@/assets/*": ["assets/*"],
"@/components/*": ["components/*"],
"@/config/*": ["config/*"],
"@/models/*": ["models/*"],
"@/navigator/*": ["navigator/*"],
"@/pages/*": ["pages/*"],
"@/utils/*": ["utils/*"]
}
完毕
自己测试一下能否使用