Skip to main content




Me target con este artículo era establecer una configuración simple que luego se pueda desarrollar. Ha sido una lucha para entender Webpack. 

What I plan to do is do a search functionality with some fake (or real) JSON data. In this post by schooljavascript.com, I will go through my project setup.

Make a new project and cd into it:

mkdir react_search cd react_search

Create a file package.json :

npm init

If you want to skip all questions, add the mark -Y:

npm init -y

We need to install webpack as a dependency dev and webpack-cli so you can use webpack on the command line:

npm i webpack webpack-cli -D
  • i: install
  • -D: - save-dev

Create a folder src with index.js and put the following code as an example:

console.log ("hello");

Now add the following scripts to you package.json:

[/ php]

{
"Name": "react_search",
«Version»: «1.0.0»,
«Description»: «Search application using React»,
"Main": "index.js",
"Scripts": {
«Start»: »webpack –mode development«,
»Build«: »webpack –mode production»
},
»Keywords«: [],
»Author«: »,
«License»: «ISC»,
"DevDependencies": {
"Webpack": "^ 4.0.1",
"Webpack-cli": "^ 2.0.10"
}
}

[/ php]

The Webpack 4 now it has two modes; developing and production where the code is minimized in the latter.

See for yourself, running:

npm run start

This will create a dist folder with the file main.js inside (which contains your code src).

Now run:

npm run build

Setting up React and Babel

To work with React, we need to install it together with Babel. This will transfer the code from ES6 to ES5, ya que no todos los browsers son compatibles con ES6 yet (for example, Internet explorer).

Install React, and React as a dependency.

npm I react reaction-sun -S

Then install babel-core , babel-loader , babel-preset-env and babel-preset-react as a dev dependency:

npm i babel-core babel-loader babel-preset-env babel-preset-reaction -D

  • babel-core: transform your ES6 code into ES5
  • babel-loader: asistente de paquete Web para transformar tus dependencias de JavaScript (por ejemplo, cuando importas sus componentes a otros componentes) con Babel
  • babel-preset-env: determine which transforms / plugins to use and polyfills (proporciona funcionalidad moderna en navegadores antiguos que no lo admiten de forma nativa) en función de la matriz de browser que deseas admitir
  • babel-preset-react: Babel preset for all accessories React, for example, to convert JSX in functions

We need to create a file webpack.config.js to set the rules for our babel loader.

Then we need to make a separate file called .babelrc to provide the options for babel-loader. You can include it in the file webpack.config.js, but I have seen that most projects have this separate. This results in clearer readability, and can be used by other tools not related to the web package. When you declare that you are using babel-loader in your web package configuration, it will look for the file .babelrc Yes there is one.

Then change your file index.js to represent a component:

We will also need to create a file index.html in the folder src where we can add our section element with id index. This is where we render our main React component:

Now we need to install html-webpack-plugin and use it in our config file webpack. This plugin generates a file HTML with injected, you write it in dist / index.html and minimize the file.

Install html-webpack-plugin as a development dependency:

npm i html-webpack-plugin -D

Update the settings of the webpack in this way:

plugins: [new HtmlWebPackPlugin ({template: "./src/index.html", file name: "./index.html"});

The value that I am giving to the key template is where I look for my file HTML. The value of the file name is the name of the HTML minified that will be generated in the dist folder.

If you run now npm run start, you should see what is generated index.html on the dist folder.

Run open dist / index.html and you should see Hello React in your browser.

Creating webpack-dev-server

It's a bit tedious to keep running this command every time you want to see your changes in the browser. In order for the webpack to "see" our changes and therefore update each time we have made changes to any of our components, we can use the module webpack-dev-server.

Go ahead and install this as a dev dependency.

npm i webpack-dev-server -D

Then change the startup scripts from package.json So:

{"name": "react_search", "version": "1.0.0", "description": "Search application using React", "main": "index.js", "scripts": {"start": " webpack-dev-server --mode development --open "," build ":" webpack --mode production "}," keywords ": []," author ":" "," license ":" ISC "," dependencies ": {" react ":" ^ 16.2.0 "," reaction-dom ":" ^ 16.2.0 "" devDependencies ": {" babel-core ":" ^ 6.26.0 "," babel-loader " : "^ 7.1.4", "babel-preset-env": "^ 1.6.1", "babel-preset-react": "^ 6.24.1", "html-webpack-plugin": "^ 3.0. 6 "," webpack ":" ^ 4.1.1 "," webpack-cli ":" ^ 2.0.10 "," webpack-dev-server ":" ^ 3.1.0 "}}

If you run now npm run start you should see localhost: 8080 open in your default browser, that's what the flag is for —-Open. Now every time you make changes, the page will refresh.

You can also add a –hot flag to you script Of start npm which will allow you to reload only the component that has changed instead of performing a full page reload.

Configuring CSS

The last part involves setting up our CSS. Since we will import CSS files into our React components, we need the module css-loader to solve them. Once that's resolved we also need a style loader to inject this into our DOM, adding a tag in the element of our HTML.

Go ahead and install both modules as a development dependency:

npm i css-loader style-loader -D

Note that the order of adding these chargers is important. First, we need to resolve the CSS files before adding them to the DOM with the style loader. By default, the web package uses the loaders from the right (last element of the array) to the left (first element of the array).

Making CSS modular

We can also make CSS modular using webpack. Esto significa que el nombre de la clase tendrá un scope local y específico para solo el componente en cuestión.

To do this, we can provide some options for css-loader:

Since we have to give options, each charger is now an object with a pair key-value. To enable CSS modules, we need to set the module option so that css-loader be verdadero. La opción importLoaders configures how many chargers should be applied before css-loader. For example, sass-loader would have to come before css-loader.

The localIdentName allows you to configure the generated identification.

  • [Name] will take the name of your component
  • [local] is the name of your class / id
  • [hash: base64] is the randomly generated hash that will be unique in the CSS of each component

To make this a bit more visual, I'll give you an example. Let's say you have a component called Formy I have a button with a class CSS primaryButton. I also have another component called Searchy a button on it with a class CSS primaryButton. However, both classes have different CSS:

/ * Form button * / .primaryButton {background-color: green; } Search button .primaryButton {background-color: blue; }

When the web package groups your application, depending on which CSS is newer, both buttons could be green or blue instead of green and search with blue.

This is where the localIdentName goes into place. With this, once your app is packaged, your buttons will have a unique class name!

As you can see, the class name of the button in the Form component is different from that of the component Search: its name starts with the component name, the class name, and the unique hash code.

So with this, you don't have to worry about whether you've given the same class name throughout your application; you just have to worry if you have used it on the same component.

Esto concluye la primera parte de configurar una aplicación React desde cero. En la próxima publicación del Blog, mi objetivo es explicar cómo configurar las pruebas para TDD y cómo escribirlas.