记录React Native项目的搭建过程

129 阅读1分钟

记录React Native项目的搭建过程

Learn once, write(bug) anywhere. React Native官方文档

一、初始化

npx react-native init 项目名称 --template react-native-template-typescript

安装完毕后,可以启动看下是否正常

yarn start
yarn run ios

二、配置根目录

我习惯将代码放在./src下,与web项目保持一致。

  1. 先在根目录下新建文件夹src,将App.tsx移入,并更新index.js中的导入路径。
  2. 更新tsconfig
// tsconfig.json
// 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": "./",
    "paths": {
      "@/*": ["src/*"] // @代表src目录
    }
  }
}

这样在导入文件的时候就可以使用@来代表./src了。

三、添加prettier

yarn remove @react-native-community/eslint-config

yarn add -D babel-plugin-module-resolver eslint@latest eslint-config-prettier prettier

npx pod-install

删除默认的eslint配置、安装prettier与相关配置

配置eslint

// .eslintrc.js
module.exports={
  root: true,
  parser: "@typescript-eslint/parser",
  plugins: ["@typescript-eslint/eslint-plugin"],
  extends: ["prettier"],
  rules: {
    "@typescript-eslint/no-unused-vars": [
      "error",
      {
        argsIgnorePattern: "^_",
      },
    ],
    "no-unused-vars": "off",
    "no-shadow": "off",
    "@typescript-eslint/no-shadow": 1,
    "no-undef": "off",
  },
}

配置babel

// babel.config.js
module.exports = {
  presets: ['module:metro-react-native-babel-preset'],
  plugins: [
    [
      'module-resolver',
      {
        root: ['/'],
        alias: {
          '@': './src'
        }
      }
    ],
  ]
}

现在就可以按照自己的喜好配置prettier规则了,附上我个人的配置。prettier配置文档

module.exports = {
  arrowParens: 'avoid',
  singleQuote: true,
  bracketSpacing: true,
  endOfLine: 'lf',
  semi: false,
  tabWidth: 2,
  tailingComma: 'none'
}

完成!