Cómo configurar e implementar su aplicación React desde cero usando Webpack y Babel

Así que ha estado usando create-react-app también conocido como CRA durante un tiempo. Es genial y puedes empezar directamente a codificar. Pero, ¿cuándo necesita expulsar la aplicación create-react-app y comenzar a configurar su propia aplicación React? Habrá un momento en el que tendremos que dejar de lado el control de seguridad y comenzar a aventurarnos por nuestra cuenta.

Esta guía cubrirá la configuración de React más simple que he usado personalmente para casi todos mis proyectos de React. Al final de este tutorial, tendremos nuestro propio texto estándar y aprenderemos algunas configuraciones de él.

Tabla de contenido

  • ¿Por qué crear su propia configuración?
  • Configuración de webpack 4
  • Configuración de Babel 7
  • Añadiendo más bonito
  • Agregar mapa de origen para mejores registros de errores
  • Configurar ESLint
  • ¡Encontré errores! ¿Qué debo hacer?
  • Añadiendo procesador CSS LESS
  • Implementación de la aplicación React en Netlify
  • Conclusión

¿Por qué crear su propia configuración?

Hay ciertas razones por las que tiene sentido crear su propia configuración de React. Es probable que seas bueno con React y quieras aprender a usar herramientas como webpack y Babel por tu cuenta. Estas herramientas de compilación son poderosas y, si tiene algo de tiempo adicional, siempre es bueno aprender sobre ellas.

Los desarrolladores son personas naturalmente curiosas, por lo que si siente que le gustaría saber cómo funcionan las cosas y qué parte hace qué, déjeme ayudarlo.

Además, ocultar la configuración de React mediante create-react-app está destinado a los desarrolladores que comienzan a aprender React, ya que la configuración no debería ser un obstáculo para comenzar. Pero cuando las cosas se ponen serias, por supuesto, necesita más herramientas para integrar en su proyecto. Pensar en:

  • Añadiendo cargadores de paquetes web por menos, sass
  • Haciendo renderizado del lado del servidor
  • Usando nuevas versiones de ES
  • Agregar MobX y Redux
  • Haciendo su propia configuración solo por aprender

Si busca en Internet, hay algunos trucos para sortear las limitaciones de la CRA, como create-react-app rewired. Pero realmente, ¿por qué no aprender a configurar React por su cuenta? Yo te ayudaré a llegar allí. Paso a paso.

Ahora que está convencido de aprender algo de configuración, comencemos por inicializar un proyecto React desde cero.

Abra la línea de comando o Git bash y cree un nuevo directorio

mkdir react-config-tutorial && cd react-config-tutorial

Inicialice el proyecto NPM ejecutando:

npm init -y

Ahora instale reaccionar

npm install react react-dom

Además, puede ver el código fuente en GitHub mientras lee este tutorial para obtener explicaciones sobre la configuración.

Configuración de webpack 4

Nuestra primera parada será el paquete web. Es una herramienta muy popular y poderosa para configurar no solo React, sino casi todos los proyectos de front-end. La función principal de webpack es que toma un montón de archivos JavaScript que escribimos en nuestro proyecto y los convierte en un solo archivo minificado, para que sea rápido de servir. A partir de webpack 4, no estamos obligados a escribir un archivo de configuración para usarlo, pero en este tutorial escribiremos uno para que podamos entenderlo mejor.

Primero, hagamos una instalación

npm install --save-dev webpack webpack-dev-server webpack-cli

Esto instalará:

  • módulo webpack , que incluye todas las funciones básicas del paquete web
  • webpack-dev-server : este servidor de desarrollo vuelve a ejecutar automáticamente el paquete web cuando se cambia nuestro archivo
  • webpack-cli : habilita la ejecución de webpack desde la línea de comandos

Intentemos ejecutar webpack agregando el siguiente script a package.json

"scripts": { "start": "webpack-dev-server --mode development", },

Ahora cree un index.htmlarchivo en su proyecto raíz con el siguiente contenido:

   My React Configuration Setup 

Cree un nuevo directorio con nombre srcy dentro de él, cree un nuevo index.jsarchivo

mkdir src && cd src && touch index.js

Luego escribe un componente React en el archivo:

import React from "react"; import ReactDOM from "react-dom"; class Welcome extends React.Component { render() { return 

Hello World from React boilerplate

; } } ReactDOM.render(, document.getElementById("root"));

Ejecute el paquete web usando npm run start… Y se activará un error.

You may need an appropriate loader to handle this file type

Configuración de Babel 7

El componente React que escribimos anteriormente usó la classsintaxis, que es una característica de ES6. Webpack necesita que Babel procese ES6 en sintaxis de ES5 para que esta clase funcione.

Instalemos Babel en nuestro proyecto

npm install --save-dev @babel/core @babel/preset-env \@babel/preset-react babel-loader

¿Por qué necesitamos estos paquetes?

  • @ babel / core es la dependencia principal que incluye el script de transformación de babel.
  • @babel/preset-env is the default Babel preset used to transform ES6+ into valid ES5 code. Optionally configures browser polyfills automatically.
  • @babel/preset-react is used for transforming JSX and React class syntax into valid JavaScript code.
  • babel-loader is a webpack loader that hooks Babel into webpack. We will run Babel from webpack with this package.

To hook Babel into our webpack, we need to create a webpack configuration file. Let’s write a webpack.config.js file:

module.exports = { entry: './src/index.js', output: { path: __dirname + '/dist', publicPath: '/', filename: 'bundle.js' }, devServer: { contentBase: './dist', }, module: { rules: [  test: /\.(js ] }, };

This webpack config is basically saying that the entry point of our application is from index.js, so pull everything that’s needed by that file, then put the output of the bundling process into the dist directory, named bundle.js. Oh, if we’re running on webpack-dev-server, then tell the server to serve content from contentBase config, which is the same directory this config is in. For all .js or .jsx files, use babel-loader to transpile all of them.

In order to use Babel presets, create a new .babelrc file

touch .babelrc

Write the following content:

{ "presets": [ "@babel/preset-env", "@babel/preset-react" ] }

Now run npm run start again. This time it will work.

Adding Prettier

To further speed up development, let’s make our code formatter using Prettier. Install the dependency locally and use the — save-exact argument since Prettier introduces stylistic changes in patch releases.

npm install --save-dev --save-exact prettier

Now we need to write the .prettierrc configuration file:

{ "semi": true, "singleQuote": true, "trailingComma": "es5" }

The rules means that we want to add semicolon for the end of every statement, use a single quote whenever appropriate and put trailing commas for multi-line ES5 code like objects or arrays.

You can run Prettier from the command line with:

npx prettier --write "src/**/*.js"

Or add a new script to our package.json file:

"scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "webpack-dev-server --mode development", "format": "prettier --write \"src/**/*.js\"" },

Now we can run Prettier using npm run format.

Additionally, if you’re using VSCode for development, you can install the Prettier extension and run it every time you save your changes by adding this setting:

"editor.formatOnSave": true

Adding source map for better error logs

Since webpack bundles the code, source maps are mandatory to get a reference to the original file that raised an error. For example, if you bundle three source files (a.js, b.js, and c.js) into one bundle (bundler.js) and one of the source files contains an error, the stack trace will simply point to bundle.js. This is problematic as you probably want to know exactly if it’s the a, b, or c file that is causing an error.

You can tell webpack to generate source maps using the devtool property of the configuration:

module.exports = { devtool: 'inline-source-map', // … the rest of the config };

Although it will cause a slower build, it has no effect on production. Sourcemaps are only downloaded if you open the browser DevTools.

Setting up ESLint

Linter is a program that checks our code for any error or warning that can cause bugs. JavaScript’s linter, ESLint, is a very flexible linting program that can be configured in many ways.

But before we get ahead, let’s install ESLint into our project:

npm --save-dev install eslint eslint-loader babel-eslint eslint-config-react eslint-plugin-react
  • eslint is the core dependency for all functionalities, while eslint-loader enables us to hook eslint into webpack. Now since React used ES6+ syntax, we will add babel-eslint — a parser that enables eslint to lint all valid ES6+ codes.
  • eslint-config-react and eslint-plugin-react are both used to enable ESLint to use pre-made rules.

Since we already have webpack, we only have to modify the config slightly:

module.exports = { // modify the module module: { rules: [jsx)$/, exclude: /node_modules/, use: ['babel-loader', 'eslint-loader'] // include eslint-loader ] }, };

Then create an eslint config file named .eslintrc with this content:

{ "parser": "babel-eslint", "extends": "react", "env": { "browser": true, "node": true }, "settings": { "react": { "version": "detect" } } }

The config is basically saying, “Hey ESLint, please parse the code using babel-eslint before you check it, and when you’re checking it, please check if all the rules from our React rules config is passed. Take global variables from the environment of browser and node. Oh, and if it’s React code, take the version from the module itself. That way the user won’t have to specify the version manually.

Rather than specifying our own rules manually, we simply extend react rules which were made available by eslint-config-react and eslint-plugin-react.

I found errors! What do I do?

Unfortunately the only way to really figure out how to fix ESLint errors is by looking at the documentation for rules. There’s a quick way to fix ESLint errors by using eslint--fix, and it’s actually good for a quick fix. Let’s add a script on our package.json file:

"scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "webpack-dev-server --mode development", "format": "prettier --write \"src/**/*.js\"", "eslint-fix": “eslint --fix \"src/**/*.js\"", // the eslint script "build": "webpack --mode production" },

Then run it with npm run eslint-fix. Don’t worry if you’re still fuzzy about ESLint for now. You will learn more about ESLint as you use it.

Adding CSS LESS processor

In order to add the LESS processor into our React application, we will require both less and loader packages from webpack:

npm install --save-dev less less-loader css-loader style-loader

less-loader will compile our less file into css, while css-loader will resolve css syntax like import or url(). The style-loader will get our compiled css and load it up into le> tag in our bundle. This is great for development because it lets us update our style on the fly, without needing to refresh the browser.

Now let’s add some css files to create a new style directory in src/style

cd src && mkdir style && touch header.less && touch main.less

header.less content:

.header { background-color: #3d3d; }

main.less content:

@import "header.less"; @color: #f5adad; body { background-color: @color; }

Now import our main.less file from index.js:

import "./style/main.less";

Then update our webpack configuration module property:

module: { rules: [ test: /\.(js, { test: /\.less$/, use: [ 'style-loader', 'css-loader', 'less-loader', ], }, ] },

Run the start script and we’re good to go!

Deploying React app to Netlify

All applications need to be deployed for the last step, and for React applications, deployment is very easy.

First, let’s change the build output and development contentBase from dist to build in our Webpack config.

module.exports = { entry: './src/index.js', output: { path: path.resolve(__dirname, 'build'), // change this publicPath: '/', filename: 'bundle.js' }, devServer: { contentBase: "./build", }, //…

Now let’s install a new Webpack plugin named HtmlWebpackPlugin

npm install html-webpack-plugin -D

This plugin will generate index.html file in the same directory where our bundle.js is created by Webpack. In this case, the build directory.

Why do we need this plugin? Because Netlify requires a single directory to be made the root directory, so we can’t use index.html in our root directory using Netlify. You need to update your webpack config to look like this:

const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: //… output: { //… }, devServer: { contentBase: "./build", }, module: { //… }, plugins: [ new HtmlWebpackPlugin({ template: path.resolve('./index.html'), }), ] };

And please remove the script tag from your index.html:

 My React Configuration Setup My React Configuration Setup 

Now you can test the config with npm run build command. Once it’s done, push your boilerplate into a GitHub repo. It’s time to deploy our application!

Now let’s register a Netlify account. If you haven’t heard of Netlify before, it’s an amazing static site hosting that provides all the tools you need to deploy a static site for free. What’s a static site? It’s a website created from a collection of static HTML pages, without any backend. Our React boilerplate as it is now counts as a static site, because we have no backend configured and its just HTML and JavaScript.

After sign up, select new site from Git and Choose GitHub as your Git provider:

You need to grant permissions for Netlify, and then select your React boilerplate repo.

Now you need to enter the build command and publishing directory. As you can see, this is why we need HtmlWebpackPlugin, because we need to serve everything from one directory only. Rather than manually updating our root index.html file for changes, we just generate it using the plugin.

Make sure you have the same command as the screenshot above, or your app might not run.

Once the deploys status turns to published (number 2 above), you can go to the random site name Netlify has assigned for your application (number 1).

Your React application is deployed. Awesome!

Conclusion

You’ve just created your very own React project boilerplate and deploy it live to Netlify. Congratulations! Granted, I didn’t go very deep on webpack configurations, because this boilerplate is meant to be a generic starter. In some cases where we need advanced features like server side rendering, we need to tweak the configuration again.

But relax! You’ve come this far, which means you already understand what webpack, Babel, Prettier and ESLint do. Webpack has many powerful loaders that can help you with many cases you’ll frequently counter when building a web application.

Also, I’m currently writing a book to help software developers learn about React, so you might wanna check it out!

You can read more of my React tutorials at sebhastian.com.