Develop React (Native) apps like a PRO

June 06, 2017 0 Comments

Develop React (Native) apps like a PRO

 

 

Improve your code quality with few simple tools

In my daily job, I see various codebases and collaborate with a lot of developers from all over the world. I’ve noticed that many programmers don’t pay enough attention to things like code cleanness, tests or typings. All of those things are “optional” in JavaScript so you can develop apps without them, but it’s not the way to go if you’re collaborating with other devs or if your project grows larger. There are a few tools build around React which can help you improve your code quality in no time. I’ll try to briefly describe them here and give you a small boilerplate with all of them combined and set up. You can find the link at the end of this article.

ESlint is a very basic tool which provides linting utility for modern JavaScript. It’s very pluggable so you can install it globally on your machine and set it up in your IDE to have real-time checks or just simply attach it to your project. For sure the last approach is better because you can have a version targetted especially for your project and also run this kind of check on continuous integration systems. It’s very simple to start with ESlint. First you need to add it to your project:

yarn add eslint --dev
NOTE: You can use npm instead.

ESlint requires configuration placed inside .eslintrc file, or under “eslintConfig” property in your package.json. If you don’t want to spend time defining all the rules for your project, I recommend the eslint-config-airbnb package, which contains very good rules for writing good React applications. Here’s how it’s done:

npm info "eslint-config-airbnb@latest" peerDependencies

Now you should see peerDependencies versions listed within a JS object inside your console. Simply replace the hashes in the version and run:

yarn add eslint-config-airbnb eslint@^#.#.# eslint-plugin-jsx-a11y@^#.#.# eslint-plugin-import@^#.#.# eslint-plugin-react@^#.#.# 
--dev

Within the configuration file, create an “extend” key and add airbnb to an array of extensions, and you’re ready to go!

"extends": ["airbnb"]
NOTE: You can override some of the rules from this preset inside your config.

While ESlint is a great tool to analyze your code and eliminate various bugs and bad code, there is another solution with the power to unify your code style on each file with a single command. Prettier, a great tool released by Christopher Chedeau (@vjeux) and James Long (@jlongster), is an opinionated JavaScript formatter with advanced support for language features from ES2017, JSX, and Flow. It removes all original styling and ensures that all outputted JavaScript conforms to a consistent style. Like ESlint, it has plugins for various IDEs, so you can enable it when saving each file. If you don’t want to do this you can just run a CLI command or hook it to pre-commit. It’s very easy to start:

yarn add prettier --dev

When prettier is available in your project you can add a new script to your npm scripts in package.json; the entry could look like this:

"scripts": {
...
"prettier": "prettier — single-quote — trailing-comma all — write \"src/*/.js\""
},

It tells prettier to format your .js files within the src/ folder with some formatting options. You can check the full docs here.

Prettier plays along with ESlint very well — it provides some eslint presets, so if you’re using them both, don’t forget to add extensions, just like you did with the airbnb preset:

yarn add eslint-config-prettier --dev

and then:

"extends": [
"airbnb",
"prettier",
"prettier/flowtype",
"prettier/react"
],

I’ve begun my programming journey with Java. When I moved to web development, I loved the freedom JavaScript gives in everyday development, but I felt like something was missing. Everything was very well typed in Java apps, and when I heard about Flow I was very excited. Static typing helps you eliminate a lot of errors and makes the code really readable for other developers. What’s great about Flow is the fact that it plays along with your IDE in real time, just like ESlint. In React Native the .flowconfig file isalready present in the generated app. You simply have to install flow:

yarn add flow-bin --dev

To perform typecheck in your app just add the script to your package.json

"scripts": {
...
"flow": "flow",
},

Then you can run:

yarn run flow

If you want to add Flow to your web application you have to specify .flowconfig by yourself. But don’t worry — it’s super easy, just follow the docs and read this article.

If you haven’t heard about it yet, Haul is an open-source library which is a replacement for react-native packager. It allows you to access a full webpack ecosystem, so things like aliases or symlinks are easily doable. To get more info about what’s possible with Haul, please check the haul repo and the webpack docs. I’ll quickly show you how to add Haul into your project and set some aliases to avoid relative paths and make your code a bit more readable for other developers. First, you need to add haul into your project:

yarn add haul --dev
NOTE: It used to be haul-cli until June 2017.

From now on you can run the haul init script:

yarn run haul init

Notice that there is a new file called webpack.haul.js generated within your project. It provides a hook which allows you to mutate Haul’s default webpack config. There are tons of options to customize your project with webpack. I’ll show you real quick one of my favorite options, which are aliases for directories in your project. Open your webpack.haul.js and edit the exported function:

const path = require(‘path’);
module.exports = ({ platform, root }, defaults) => ({
entry: ./index.${platform}.js,
resolve: {
...defaults.resolve,
alias: {
...defaults.resolve.alias,
components: path.join(root, 'src', 'components'),
containers: path.join(root, 'src', 'containers'),
stores: path.join(root, 'src', 'stores'),
routes: path.join(root, 'src', 'routes.js'),
}
}});

In this specific case, I created aliases for components, containers, and stores directories and to the routes file.

Now within your project, you can import components like this:

import Button from 'components/Button';

Amazing, isn’t it?

If you’re using Flow inside your project, aliases will produce an error. If you want to get rid of, you need to specify module.namemapper in your .flowconfig options. The module name mapper definition for our aliases should look like this:

module.namemapper='^components/(.)'->'<PROJECT_ROOT>/src/components/\1'
module.name_mapper='^containers/(.
)'->'<PROJECTROOT>/src/containers/\1'
module.name
mapper='^stores/(.)'->'<PROJECT_ROOT>/src/stores/\1'
module.name_mapper='^routes'->'<PROJECT_ROOT>/src/routes.js'

No errors! Yay!

Testing is very important to ensure your code quality. When it comes to testing React components, Jest is my first call. It’s already bundled with RN initial project, so you don’t have to install anything. With snapshot testing, you can cover a nice amount of your code without writing a lot of code in your test files. Look how simple wring a test for the component is:

/ @flow */
import
React from 'react';
import renderer from 'react-test-renderer';
import Button from '../Button';
describe('<Button />', () => {
it('should render correctly', () => {
const tree = renderer.create(<Button />).toJSON();
expect(tree).toMatchSnapshot();
});
});

If you want to learn more about snapshot testing check out this great article.

There is a lot of other tools and libraries to help you increase your development capabilities. I put everything you read today and some other cool libs inside an example app. If you want to learn more about other tools, I recommend reading this article.

Mike.


Tag cloud