Marvelous Thorough React Tutorial/Workshop — part 2
This series of articles is written as notes used during the workshop hosted in Gdańsk, Poland by OKE Software Poland. It does not pose as comprehensive and complete tutorial serie for anyone, yet it will be used for workshop aimed for developers that have none experience building SPA using React. I am posting it here as I think some people might find it useful. Please do not hesitate to correct my, if you find me writing nonsense. Also please bear in mind that english isn’t my native language, so forgive my any grammar and linguistic mistakes. My third article! Enjoy!
BTW here’s previous part ->

Plan
Part 2 - Prettier, Yarn Scripts, ESLint, Webpack, JSX
You remember those good old times when you could just add jQuery script tag to your html file or even better use VanillaJS and be on your way to building your new shiny web app? Well, these are no more. There’s this kinda strange tradeoff where you have to set up a bunch of tools just to get your development environment on track. Configuration can be time consuming and hard at first, but what you get in return is great set of tools and helpers that will make your life easier in a long run. You can naturally skip all that and go on working with React as I show in previous part. You can also decide that you’re not interested in setting those tools by yourself and rely on some boilerplate project or tool like create-react-app, which basically configures everything just for you:
It’s all fine, but I believe that before using something like create-react-app is nice to know how this stuff actually works under the hood. Let’s shed some light on it.
Prettier
Remember when you had that fight with your coworker discussing for hours the superiority of tabs compared to spaces for indentation? Or the precious minutes you’ve spent to decide what is the desired line length for your file to maintain the readability? Or when you couldn’t decide whether to add the trailing comma or get rid of it? And many, many different situations about code formatting that simply took out the time of your development and kicked you out of your development zen into the frustrating code-janitor work?
You can wave them all goodbye for here is Prettier. You and you team won’t have to worry about code style no more. If you want to read more about it or try it
Seriously I can’t recommend this tool enough. It basically takes your code, strips away all code styling and applies the predefined set of rules to it reformatting whole output.
Let’s add it to our project:
yarn add --dev prettier— dev option passed to command makes the dependency marked as used only for development process instead of the dependency that our built, working app actually cares about. This will add prettier as our local dependency in node_modules and to run it we will type:
./node_modules/.bin/prettier index.jsThis command will output the reformatted file content to the standard output (terminal window). What if we’d like to actually save the formatted version of the file? Piece of cake:
./node_modules/.bin/prettier index.js --writeWow, that is neat! But it’s kinda stupid to write this one everytime we’d like to format our file, right?
This gets us to:
Yarn/NPM Scripts
I strongly believe that you should automate any boring or repeating stuff. That’s what computers are for. Many tasks like clearing build folder, building, linting, prettiering (if that’s a word) and others should be integrated into the IDE or into simple scripts that you should be able to run with one command. NPM does great job with that one with npm scripts. Let’s try writing our first npm script. Open your package.json file and add this to the file:
"scripts":{
"prettify": "prettier --write --single-quote --print-width=90 \"js/**/*.{js,jsx}\""js
}Now in terminal you can just run:
yarn prettifyor
npm run prettifyand voila!
Prettier in VS Code
Of course we can still do better than this and plug Prettier into our IDE, to prettify our file on save. Let’s install Prettier — JavaScript formatter package by typing Prettier in extension tab in VS Code and choosing the one with most downloads:

Once it is done we can do some fun stuff for example. You can select part of text (or empty space in document) click left and choose:

It will format the selection/document accordingly. Alternatively you can press cmd + shift + p, type format and press enter or use alt + shift + f to format document. It works great, but we can still enhance it a little bit. Press cmd + , (comma) to display default and user settings. Type prettier in search bar to display all the settings regarding prettier, you can see many options regarding prettier there that you can change to match your style, but the one that we’d like to change right now is a little different. Search for :
editor.formatOnSaveCopy it to user settings and change its value to true and save settings by hitting cmd + s:

Now mess up the index.js file anyway you’d like and hit save (cmd +s again).

Remember that you can tweak the options of Prettier using VS Code user settings. The only thing left to do is to sit down with your teammates and agree on prettier options and you’re all set with code styling :).
Also please be sure to find few minutes to watch:
https://www.youtube.com/watch?v=hkfBvpEfWdA
ESLint
Here is simple truth:
As project grows we often forget to pay attention to details in our code, like:
- Do I still use this variable anywhere?
- Do I actually mutate this variable?
- Did I pushed the code with console.logs to the git?
- Am I adding variables/functions to global scope?
And many, many more good practices and stylistic issues that are just hard to always have in mind while coding. Going along those guides is mental expense draggins us away from what we are actually trying to solve. It is really great to remember about them and be aware of them, but what if we can get some assistance regarding checking our code against set of rules?
Behold ESLint pluggable JavaScript linting utility tool. It is another fantastic piece of software that we’ll be using in our workshop. Let’s add it to our devDependencies.
yarn add --dev eslintESLint is another tool that exposes many options and is fully configurable. We can specify what exactly we expect from using package.json file and adding the "eslintConfig" and specyfing options there, but I kinda feel this is a little bit different topic and should be separated (it’s up to you to decide which style suits you better) into another file. The .eslintrc file created in root of your folder will be automatically picked up by ESLint as configuration. Let’s add one right now.
There are few options that we’d like to specify definitely while using ESLint. You can tell the linter which rules are you interested in using and whether to treat any derogation from them as warnings and errors. The full set of rules can be found in:
Yet, there’s more simple approach using extends keyword, which basically means you’d like to extend set of rules specified by someone else. Pretty nice. I’d like to recommend few. If you’re interested in functional programming you should try this one:
But as functional techniques are out of scope of this workshop, we’ll go with the set of rules from airbnb, which is very popular and suits our needs. Run:
yarn add --dev eslint-config-airbnb-base eslint-plugin-import eslint-plugin-react eslint-plugin-jsx-a11y eslint-config-airbnbOnce this dependencies are added to our project, open .eslintrc file and add:
{
"extends": "airbnb"
}And to give it a spin with:
./node_modules/.bin/eslint .And we get the short raport of the problems/broken rules/style guiding. As stated at the end of the report we can pass --fix option to fix part of them automatically, let’s try that!
./node_modules/.bin/eslint **/*.{js,jsx} --fixMuch better isn’t it? Lets append those to our npm scripts.
"scripts": {..."lint": "eslint **/*.{js,jsx}"},
So now calling it as yarn lint will produce the output that we’d like to see, but still we can ask ESLint to fix things that it knows how to fix, by passing the --fix option. How? Just type yarn lint -- --fix. The first dashes specify options that we’d like to pass directly to the NPM and then the set of flags for the command that we are executing itself. This is nice and neat, but let’s add some flavor to it. We definitely want out prettier to play nicely with ESlint so these two don’t get in each others way. Let’s add few dependencies:
yarn add --dev eslint-config-prettier eslint-config-react eslint-plugin-prettierOk, we will extend our .eslintrc file further also adding the settings for ESLint parser that we’d like to use and environments in which we’ll be running our code.
We also wanna change to settings for some rules as they seem to be a little broken in the latest version of jsx-a11y. Ok, how about VSCode integration? Just go to your Extensions tab and install ESLint. Than go to your index.js file and see the results!

This is where we finish with ESLint configuration for now :).
Webpack & Babel
There are many tasks regarding frontend project that often has to be repeated for build process. Minification, concatanation, file parsing, copying, changing scss/sass back to css files, file renaming and so on. That’s were build tools come in. Many of you probably have heard of Grunt, Gulp or Webpack. I really like Gulp as a solution, because it’s based on streams, which kinda remainds me .map operation where you are putting your input through the series of transformation to get desired output, but Webpack composes so well with React ecosystem, that it became the most popular solution. We’ll use it just for some basic stuff, but if you’d like to learn more about this fantastic tool reach out to:
They have a free course about Webpack which explains a lot! What you need to know for the time being is that Webpack is basically a file bundler, that can handle different types of file in different way and spit out one bundle or many chunks as a result. Why we need that? Well, remember the good, old days when you had add script tag for every single js file that you wanted to incorporate into your app? And god forbid if they depend on each other because you have to ensure the correct order of loading them or else your app could crash because of Reference Error. Not to mention that most of your variables, functions and modules existed in global scope.
Ok let’s add webpack to our project:
yarn add --dev webpackDone? Done. Ok Now let’s split our file into two. Create js folder in the root of your project and move your index.js there. Rename it to App.js and take the code creating the topBarTitle and put it in the same folder to TopBarTitle.js. Ok go back to App.js and add at the top:
import topBarTitle from './TopBarTitle'What is this? Welcome to ES6 modules. If you have never used commonJS or ES6 modules this may seem a little confusing to you, but basically this is the way that we can now seperate files, concern and provide interfaces in ES6. Earlier we would rely on IFEE to create modules, but they still were attached to the global scope. Well, no more. As Radiohead sang: Everything in it’s right place :).
Ok once the webpack is done bundling our files. It will spit out… well… a bundle. Let’s attach this to our index.html.
Ok now we can execute our command to let webpack know what is that we exactly want from it:
./node_modules/.bin/webpack js/App.js public/bundle.jsOk, so we need our webpack to take js/App.js file and bundle it and its dependencies (imported modules, in this case TopBarTitle) and provide us with the result as public/bundle.js. After you execute this command you will see a simple summary in your terminal:

We can see name, size and what files were used in the build process. Pretty nice isn’t it? Of course check if our index.html file still works. You are more than welcome to check out public/bundle.js file for its content.
Time to push a branch -> step3-eslint-basic-webpack-conf
Ok let’s naturally add this to our scripts in package.json add:
"bundle": "webpack js/App.js public/bundle.js"And run it with yarn bundle.
Babel
We’re not done with the tooling yet. You may already feel overwhelmed by the amount of configuration that we need to do to set the React project up. Well, that really a lot and mostly no fun, but each tool we are adding to our setup will definitely make our life easier in the long run. Of course once you know how they all work and what they do, you are more than welcome to use create-react-app.
Writing our component using React.createElement can be tiring and too verbose, so we’d like to use JSX, the problem is that the browsers have no idea what JSX is. Also we’d like to use some cool features from ES6, ES7 (hello async await!), but not all of these features are implemented in all the browsers in the same way. So we need to use a tool that can transpile JSX to JS and ES6, ES7 to ES5. We’ll be using Babel as another natural choice for React ecosystem, but it’s not the only one nor the first one.
Ok let us add babel to our project
yarn add --dev babel-cli babel-preset-env babel-preset-reactIn the root of your project create .babelrc file as configuration for Babel:
We specify the preset to be react. Presets are basically sets of babel-plugins bundled in one. We also tell babel to aim for two last versions of browser when it comes to environment. Also as Webpack 2 has ability to do tree shaking we tell Babel not to transform modules. What’s that about? Well as we are using ES6 modules, telling exactly what we are importing to and exporting out of modules, we are basically building a graph of dependencies. If given module is not used in your code it won’t be bundled and shipped to client. So only the used functions will be included into generated bundle.js. We “shake off” the unused code, which is great reduction of bundle size. You definitely could use babel command line interface to transpile your code, but we’d like to automate this process using Webpack. Webpack is doing its file transformations with entities called loaders. There are css loader, image, file, babel loader and many, many more. Let’s add babel-loader to our dev dependencies
yarn add --dev babel-loaderand then we can call:
./node_modules/.bin/webpack --module-bind 'js=babel-loader' js/App.js public/bundle.jsNice! Now are code is being transpiled through Babel, but I think that’s about the time we move from calling webpack through inline commands and move it to it’s very own configuration file. At the root of your project create webpack.config.js:
Let’s walk through it.
At the top I require the node module called path which provides the cross OS abstraction regarding the filepaths (backslash, forwardslash difference). At the beginning of the configuration we inform webpack of the context of execution being our root directory. We specify the entry file being App.js.We tell webpack to create source maps. Because all the files are going to be bundled and passed to browser as one, we lose the ability to easily debug our code. Source maps are like markings tracing our bundled code back to the readable and debuggable version of code, basically looking the same as the code we’ve written in our IDE. Then we specify where to output the bundle. Than we ask webpack to automatically resolve import names for some extension this enables us to write:
import topBar from './topBar'instead of
import topBar from './topBar.js' or
import topBar from './topBar.jsx'Stats are basicall configuration of what is printed in your terminal after the webpack finishes the build. And than the last, but not least the module object. Here we specify what loaders (transformations) should be applied to what type of files. Currently we only want to transform js and jsx files and pass them through to babel-loader for transpilation to ES5 syntax, so that every browser can understand our code. Ok go to your package.json and change our bundle script to:
"bundle":"webpack"Wow that is nice! But there’s one little thing that we need to change. If you run our linting script right now, you will see a lot of errors! Why is that? Well, linter is now linting public and node_modules two because we didn’t tell it to omit those. Let’s fix that right away. In your root folder add .eslintignore file:
node_modules/
public/Now, we get report only from the files we are interested in.
Neat. I will and this part here. We’ll start the next one with JSX and then move to React components. Cheers and stay tuned for the next part!
