Me target¿Qué es un objetivo?En marketing, un objetivo es el resultado que se pretende alcanzar en un periodo de tiempo, a través el uso de los recursos disponibles. Por tanto, se debe formular de una forma clara y hace falta que sea accesible y medible. plus 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 indexUn index o índice es generalmente un directorio en un orden específico que se usa con fines de orientación. En términos de motores de búsqueda, un índice es la lista de páginas web que es emitido por el motor de búsqueda en respuesta a una solicitud de búsqueda del usuario. Información general La lista que se muestra posteriormente de introducir una solicitud de búsqueda específica se llama SERPs (Search Engine plus.js and put the following code as an example:

console.log ("hello");

Now add the following scriptsConcepto de Scripts¿Qué son los Scripts?Los Scripts son fragmentos de código que se usan para dar forma a herramientas tanto en Internet como en el sector de la informática en general. Son una parte crucial del software, puesto que se trata exactamente del código que conforma a una aplicación en su totalidad o a una de sus funciones, como además el que puedes hallar explorando cómo está hecha una web.Desde plus 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 browsersConcepto de Navegadores¿Qué son los Navegadores?Los Navegadores son herramientas informáticas que utilizamos para, normalmente, navegar por Internet y visitar cualquier página web, al mismo tiempo de para hacer otras tareas como ver documentos, observar vídeos o reproducir contenido multimedia de cualquier tipo. Son un tipo de software sencillamente usual y bastante utilizado hoy en día.Insistimos en que es algo que se utiliza con mucha frecuencia, puesto que moverse por Internet plus 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 JavaScriptJavaScript es un lenguaje de programación que funciona en el lado del cliente y con el que las webs pueden ser más funcionales. Incorporación en código HTML El código JavaScript puede ser incrustado en las páginas HTML, para que adquieran funcionalidad. Existen varias opciones. Puede estar entre las etiquetas <SCRIPT> y </SCRIPT>, puede estar contenido en un archivo externo, puede ser un parámetro de las etiquetas HTML, y puede estar plus (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 browserUn navegador (además: browser) es una herramienta informática que te permite ver documentos y datos y navegar por la red. Los navegadores pueden mostrar distintos tipos de recursos de información; principalmente documentos HTML, a pesar de todo, además son posibles otros tipos de archivos y contenido multimedia, como PDF, JPEG, MPEG, GIF o el lenguaje de meta marcado. A través el uso de complementos especiales y la configuración respectivo, los plus 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 HTMLHTML (Hypertext Markup Language) se usa para estructurar el contenido de texto de un documento web. No sólo se marca el contenido, sino además la meta-información que describe este contenido. Las páginas HTML se almacenan normalmente en el directorio raíz del servidor. Cómo se creó En la era digital, a los usuarios les resulta difícil hallar su camino en las webs y hacer un seguimiento de las estructuras de las plus 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 CSSConcepto de CSS¿Qué es el CSS?CSS es un lenguaje de programación que se usa para definir el estilo y el aspecto de un documento que se ha escrito mediante de un lenguaje de etiquetas, como HTML. Conocido además como hojas de estilo en cascada, es el que se emplea para dar colores, indicar tipos de letra o inclusive resaltar aspectos como el espacio entre items para dotar de estilo a plus

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. This means that the class name will have a local and specific scope for only the component in question.

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 true. The option 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 BlogEl término blog se usa para describir un diario virtual en Internet. El autor de un blogger puede publicar posts sobre cualquier tema. Los posts suelen estar presente de forma cronológica. El estilo de redacción de un blog suele ser informal y se escribe en primera persona. No obstante, además son posibles otros estilos, por ejemplo en el caso de los periódicos online, en los que la atención se centra plus, mi objetivo es explicar cómo configurar las pruebas para TDD y cómo escribirlas.