1. 初始化我的项目
创立我的项目
应用 react-native
脚手架创立一个名字叫 rn-demo
的我的项目,应用官网 typescript
模板。
npx react-native init rn_demo --template react-native-template-typescript
留神:项目名称不能应用 -
字符,脚手架不反对。
运行我的项目
yarn ios
或者
yarn android
创立文件
如下图所示:
接下来要给src/utils
门路配置别名。
2. 编辑 tsconfig.json
设置别名
用来给 .ts
和 .tsx
引入文件的时候解析门路别名应用。
{ "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打包的时候解析门路别名应用,不配置的话,运行过程中会报错,找不到文件。
yarn add -D babel-plugin-module-resolver
编辑 babel.config.js
配置插件
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
编写测试代码:
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;
运行
yarn start --reset-cache
肯定要记得退出 --reset-cache
标记清理缓存,否则配置不会失效。
后果
参考:官网指南
❤️反对
如果本文对你有帮忙,点赞反对下我吧,你的「赞」是我创作的能源。