React Native系列(一) - 创建项目及基础配置

Yukino 917 2022-08-24

最近开始做一个RN项目,之前没怎么接触过,遇到些问题,就边做边记吧

一、环境搭建

React Native的官方文档步骤还挺完善的,这里就不赘述了,主要的一点就是涉及到安卓的需要有稳定的代理软件。

二、项目创建

我这里是直接拉取的文档中的TS模板项目:

npx react-native init AwesomeTSProject --template react-native-template-typescript

但我感觉其中还有些东西需要配置。

三、prettier配置

首先是Prettier,我换成了自己习惯的配置:

{
  "useTabs": false,
  "tabWidth": 2,
  "printWidth": 100,
  "singleQuote": true,
  "trailingComma": "none",
  "bracketSpacing": true,
  "semi": true
}

四、路径alias配置

由于这个项目使用的babel,所以我们这里直接配置babel来实现。

  1. 安装所需插件:
yarn add -D babel-plugin-module-resolver
  1. 配置babel.config.js,添加一项plugins,按如下配置:
module.exports = {
  presets: ['module:metro-react-native-babel-preset'],
  plugins: [
    [
      'module-resolver',
      {
        root: ['./'],
        alias: {
          '^~/(.+)': './js/\\1'
        }
      }
    ]
  ]
}

这样所有的~/*都会转换成./js/*

  1. 配置tsconfig.json,在文件中添加baseUrl和path,以便IDE可以识别alias
// prettier-ignore
{
  "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": "./js/",
    "paths": {
      "~/*": ["./*"]
    },
    "jsx": "react-jsx"
  }
}

五、配置JSX/TSX转换

JSX/TSX文件都需要import React from 'react',这点着实感觉有点麻烦,好在React17已经和babel合作推出了自动转换的插件,具体可见介绍全新的 JSX 转换,但是RN需要额外配置,下面记录下配置过程:

  1. 安装插件,官方给了两个插件@babel/preset-react@babel/plugin-transform-react-jsx,其中前者是包括后者的,里面还预设了一些React的相关的配置,所以这里选择前者;
yarn add -D @babel/preset-react
  1. 配置babel.config.js,需要在presets中添加@babel/preset-react,并在metro-react-native-babel-preset中将useTransformReactJSXExperimental设置为true
module.exports = {
  presets: [
    [
      'module:metro-react-native-babel-preset',
      {
        useTransformReactJSXExperimental: true
      }
    ],
    ['@babel/preset-react', { runtime: 'automatic' }]
  ],
  plugins: [
    [
      'module-resolver',
      {
        root: ['./'],
        alias: {
          '^~/(.+)': './js/\\1'
        }
      }
    ]
  ]
}
  1. 配置metro.config.js,将experimentalImportSupport更改为true:
/**
 * Metro configuration for React Native
 * https://github.com/facebook/react-native
 *
 * @format
 */

module.exports = {
  transformer: {
    getTransformOptions: async () => ({
      transform: {
        experimentalImportSupport: true,
        inlineRequires: true
      }
    })
  }
};

六、完善eslint

这里主要是加上了react-hooks,然后配置了下忽略JSX/TSX文件中的import React以及允许inline style:

module.exports = {
  root: true,
  extends: [
    '@react-native-community',
    'plugin:react-hooks/recommended',
    'plugin:prettier/recommended'
  ],
  parser: '@typescript-eslint/parser',
  plugins: ['@typescript-eslint'],
  overrides: [
    {
      files: ['*.ts', '*.tsx'],
      rules: {
        '@typescript-eslint/no-shadow': ['error'],
        'no-shadow': 'off',
        'no-undef': 'off',
        // 由于使用了@babel/preset-react自动在JSX、TSX文件中import React,所以eslint会提示warning
        'react/react-in-jsx-scope': 'off',
        'react-native/no-inline-styles': 'off'
      }
    }
  ]
};

七、配置editorconfig

主要用于统一IDE文件格式,根目录创建.editorconfig

root = true

[*] # 表示所有文件适用
charset = utf-8 # 设置文件字符集为 utf-8
indent_style = space # 缩进风格(tab | space)
indent_size = 2 # 缩进大小
end_of_line = lf # 控制换行类型(lf | cr | crlf)
trim_trailing_whitespace = true # 去除行首的任意空白字符
insert_final_newline = true # 始终在文件末尾插入一个新行

八、更改maven源

参考官方文档

尝试阿里云提供的maven 镜像,将android/build.gradle中的jcenter()google()分别替换为maven { url 'https://maven.aliyun.com/repository/jcenter' }maven { url 'https://maven.aliyun.com/repository/google' }(注意有多处需要替换)。

至此,项目就算创建、基础配置完成了。