【转】react-native之路径别名配置

1. 初始化项目

创建项目

使用 react-native 脚手架创建一个名字叫 rn-demo 的项目,使用官方 typescript 模板。

1
2
npx react-native init rn_demo --template react-native-template-typescript
复制代码

注意:项目名称不能使用 - 字符,脚手架不支持。

运行项目

1
2
yarn ios
复制代码

或者

1
2
yarn android
复制代码

创建文件

如下图所示:

image-20220827112659058.png

接下来要给src/utils路径配置别名。

2. 编辑 tsconfig.json 设置别名

用来给 .ts.tsx 引入文件的时候解析路径别名使用。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
{
"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": {
"*": ["src/*"],
}
}
}

复制代码

3. 加入babel插件babel-plugin-module-resolver

用于babel打包的时候解析路径别名使用,不配置的话,运行过程中会报错,找不到文件。

1
2
yarn add -D babel-plugin-module-resolver
复制代码

编辑 babel.config.js 配置插件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
plugins: [
[
'module-resolver',
{
root: ['./src'],
extensions: ['.ios.js', '.android.js', '.js', '.ts', '.tsx', '.json'],
alias: {
'*': ['./src'],
},
},
],
],
};

复制代码

4. 验证

修改 App.tsx

编写测试代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import React from 'react';
import {SafeAreaView, StyleSheet, Text} from 'react-native';

import multiply from 'utils/multiply'; // 使用别名导入模块

const App = () => {
return (
<SafeAreaView style={styles.wrap}>
<Text>2 * 3 = {multiply(2, 3)}</Text>
</SafeAreaView>
);
};

const styles = StyleSheet.create({
wrap: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
});

export default App;

复制代码

运行

1
2
yarn start --reset-cache
复制代码

一定要记得加入 --reset-cache 标记清理缓存,否则配置不会生效。

结果

image-20220827135806401.png

参考:官网指南

作者:雮尘
链接:https://juejin.cn/post/7136447878314065957