1. Initialize the project
Create project
Use the react-native
scaffolding to create a project named rn-demo
, using the official typescript
template.
npx react-native init rn_demo --template react-native-template-typescript
Note: The project name cannot use the -
character, which is not supported by scaffolding.
run the project
yarn ios
or
yarn android
Create a file
As shown below:
Next, configure an alias for the src/utils
path.
2. Edit tsconfig.json
set alias
Used to resolve path aliases when importing files for .ts
and .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. Add babel plugin babel-plugin-module-resolver
When used for babel packaging, the parsing path alias is used. If it is not configured, an error will be reported during operation and the file cannot be found.
yarn add -D babel-plugin-module-resolver
EDIT babel.config.js
configure plugin
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. Verification
Modified App.tsx
Write test code:
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;
run
yarn start --reset-cache
Be sure to add the --reset-cache
mark to clear the cache, otherwise the configuration will not take effect.
result
Reference: Official website guide
❤️ Support
If this article is helpful to you, please like and support me. Your "like" is the driving force for my creation.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。