Skip to content

Instantly share code, notes, and snippets.

@MorenoMdz
Last active September 3, 2019 02:28
Show Gist options
  • Select an option

  • Save MorenoMdz/ee7f729f5608327b705340d13c349558 to your computer and use it in GitHub Desktop.

Select an option

Save MorenoMdz/ee7f729f5608327b705340d13c349558 to your computer and use it in GitHub Desktop.
React Native boilerplate

Universal

Primeiro instale os básico para React e Android, Node / npm, Yarn Instale e configure o Android JDK 8, Genymotion / USB Device https://github.com/Rocketseat/ambiente-react-native


RN CLI

Instale o CLI do RN: yarn global add react-native-cli

Inicie um novo projeto: react-native init nome-do-projeto

Rode o projeto criado: react-native run-android _Processo lento, vai baixar e configurar várias partes do app novo. Deve ser usado novamente quando alguma dependência precisar de acesso a arquivos nativos como react-native link lib ou reiniciar o sistema operacional ou em caso de algumas falhas.

Inicie o app: react-native start _É possível passar um --reset-cache para resetar o transform cache do app.

_Em caso de falhas na build rodar cd android && ./gradlew cleanBuildCach && cd .. e em seguida react-native-start

_Em alguns casos de falha na atualização do conteúdo do app no device/emulador precisei deletar a pasta node_modules e rodar yarn novamente.


Estrutura do App

Mova o App.js para /src como index.js e mude seu import em /index.js (na raiz) to import App from './src';

Instale babel-plugin-root-import, para ter acesso universal a pastas usando o atalho ~/folder Rode yarn add babel-plugin-root-import -D Adicione para o .babel.config.js:

module.exports = {
  presets: ['module:metro-react-native-babel-preset'],
  plugins: [
    [
      'babel-plugin-root-import',
      {
        rootPathSuffix: 'src',
      },
    ],
  ],
  env: {
    production: {
      plugins: [
        'babel-plugin-root-import',
        {
          rootPathSuffix: 'src',
        },
      ],
    },
  },
};

Agora é possível usar'~/folder' para importar os arquivos sem precisar passar o caminho completo. Sempre em relação a pasta /src.

Instale eslint plugin pro babel importer yarn add eslint-import-resolver-babel-plugin-root-import -D Confirme essa configuração no .eslintrc:

,
  "settings": {
    "import/resolver": {
      "babel-plugin-root-import": {}
    }
  }

Adicione um arquivo de configuração do editor na raiz do projeto jsconfig.json contendo:

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "~/*": ["src/*"]
    }
  }
}

ou no .eslintrc

"settings": {
    "import/resolver": {
      "babel-plugin-root-import": {
        "rootPathPrefix": "~",
        "rootPathSuffix": "src"}
    }
  }

Ambiente de dev

Configure o .editorconfig:

root = true

[*]
charset = utf-8
indent_style = space
indent_size = 2
end_of_line = lf
trim_trailing_whitespace = true
insert_final_newline = true

_É possível gerar esse arquivo facilmente com o plugin do VSCode.

Reactoron (take a deep breath and go!): (roda bem +- no linux, se necessário use o programa cpulimit e deixe somente 20% disponível para o reactotron) Instale o programa Reactotron a partir de https://github.com/infinitered/reactotron/releases Rode yarn add reactotron-react-native Adicione um arquivo em src/config/ReactotronConfig.js contendo:

import Reactotron from 'reactotron-react-native';

if (__DEV__) {
  const tron = Reactotron.configure({ host: '192.168.0.21' }) // host needed for USB debugging
    .useReactNative() // add all built-in react native plugins
    .connect(); // let's connect!

  console.tron = tron; // you can now use `console.tron.log(stuff)`

  tron.clear(); 
};

Para usar com dispositivo USB é preciso passar o seu host no configure({}) com o seu ip da rede local da sua máquina Feche os terminais, o editor, o programa Reactotron e se preciso reincie o sistema

Importe a configuração criada no seu app(src/index.js) import './config/ReactotronConfig'

ReactDevTools, adicione um arquivo config DevToolsConfig.js na pasta src/config Importe it tno index.js import './config/DevToolsConfig'; yarn add react-devtools Adicione um script em package.json "react-devtools": "react-devtools",

Adicione alguns scripts helpers para manejo do device via USB no package.json

    "reload": "adb shell input keyboard text 'rr'",
    "devmenu": "adb shell input keyevent 82",
    "debug": "adb shell input keyevent 82 && adb shell input keyevent 61 && adb shell input keyevent 66 && adb shell input keyevent 66"

Rodando yarn run reload por exemplo parar recarregar o app no device ou yarn run devmenu para carregar o devmenu sem precisar sacodir o device.


ES-lint & Prettier

Instale eslint yarn add eslint -D Rode yarn eslint --init Configure conforme preciso, sugerido: JS modules> > React > None > Popular style guide > JSON then accept with 'Y' Remova o arquivo package.lock.json e rode yarn para atualizar a lista de dependências do projeto Instale yarn add babel-eslint -D Instale os plugins do eslint e do prettier no VSCode Configure o VSCode para ter integração com eslint prettier eslint integreation: true Configure o VSCode para formatar ao salvar formatOnSave: true No arquivo .eslintrc.json adicione babel-eslint como parser, e adicione algumas regras:

{
  "parser": "babel-eslint",
  "env": {
    "es6": true
  },
  "extends": "airbnb",
  "globals": {
    "Atomics": "readonly",
    "SharedArrayBuffer": "readonly"
  },
  "parserOptions": {
    "ecmaFeatures": {
      "jsx": true
    },
    "ecmaVersion": 2018,
    "sourceType": "module"
  },
  "plugins": ["react"],
  "rules": {
    "react/jsx-filename-extension": [
      "error",
      { "extensions": [".js", ".jsx"] }
    ],
    "import/prefer-default-export": "off"
  },
  "settings": {
    "import/resolver": {
      "babel-plugin-root-import": {}
    }
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment