Introducción
Bien, supongo que has oído hablar del paquete web, por eso estás aquí, ¿verdad? La verdadera pregunta es ¿qué sabes al respecto? Es posible que sepa algunas cosas al respecto, como cómo funciona, o puede que no tenga la menor idea. De cualquier manera, puedo asegurarle que después de leer este artículo, probablemente se sienta lo suficientemente cómodo con toda la situación del paquete web .
Después de todo, la necesidad es la madre de la invención ...
Una forma perfecta de decir por qué existe el paquete web es la cita anterior. Pero para entenderlo mejor tenemos que remontarnos, mucho tiempo atrás, a cuando JavaScript no era lo nuevo y sexy, en esas épocas antiguas en las que un sitio web era solo un pequeño paquete de cosas buenas . html, CSS y probablemente uno o varios archivos JavaScript en algunos casos. Pero muy pronto todo esto iba a cambiar.
¿Cual fue el problema?
Toda la comunidad de desarrolladores estuvo involucrada en una búsqueda constante para mejorar la experiencia general del usuario y del desarrollador en torno al uso y la creación de aplicaciones web / javascript. Por lo tanto, vimos muchas bibliotecas y marcos nuevos .introducido.
Algunos patrones de diseño también evolucionaron con el tiempo para brindar a los desarrolladores una forma mejor, más poderosa pero muy simple de escribir aplicaciones JavaScript complejas. Antes, los sitios web ya no eran solo un paquete pequeño con una cantidad impar de archivos. Afirmaron que se volvieron voluminosos con la introducción de módulos JavaScript , ya que escribir pequeños fragmentos de código encapsulados era la nueva tendencia. Eventualmente, todo esto condujo a una situación en la que teníamos 4 o 5 veces la cantidad de archivos en el paquete general de la aplicación.
No solo fue un desafío el tamaño general de la aplicación, sino que también hubo una gran brecha en el tipo de código que los desarrolladores estaban escribiendo y el tipo de código que los navegadores podían entender. Los desarrolladores tuvieron que usar una gran cantidad de código auxiliar llamado polyfills para asegurarse de que los navegadores pudieran interpretar el código en sus paquetes.
Para responder a estos problemas, se creó el paquete web. Webpack es un paquete de módulos estáticos.
Entonces, ¿cómo fue Webpack la respuesta?
En resumen, Webpack revisa su paquete y crea lo que llama un gráfico de dependencia que consta de varios módulos que su aplicación web necesitaría para funcionar como se espera. Luego, dependiendo de este gráfico, crea un nuevo paquete que consiste en la cantidad mínima de archivos requeridos, a menudo un solo archivo bundle.js que se puede conectar al archivo html fácilmente y usar para la aplicación.
En la siguiente parte de este artículo, lo guiaré paso a paso por la configuración del paquete web. Al final, espero que comprenda los conceptos básicos de Webpack. Así que pongamos esto en marcha ...
¿Qué estamos construyendo?
Probablemente hayas oído hablar de ReactJS. Si conoce reactJS, probablemente sepa qué es create-react-app . Para aquellos de ustedes que no tienen idea de cuáles son esas dos cosas, ReactJS es una biblioteca de interfaz de usuario que es muy útil para crear interfaces de usuario complejas e inteligentes, y create-react-app es una herramienta CLIpara configurar o arrancar una configuración de desarrollo estándar para hacer aplicaciones React.
Hoy crearemos una aplicación React simple pero sin usar la CLI create-react-app. Espero que esto te suene lo suficientemente divertido. :)
Fase de instalación
npm int
Así es, así es como comienzan casi todas las cosas buenas: el viejo npm init. Usaré VS Code, pero siéntase libre de usar cualquier editor de código que desee para comenzar.
Antes de que pueda hacer algo de esto, pensó, asegúrese de tener la última versión de nodeJS y npm instaladas localmente en su máquina. Haga clic en cada uno de esos enlaces para saber más sobre el proceso.
$ npm init
Esto creará un paquete de inicio y agregará un archivo package.json para nosotros. Aquí es donde se mencionarán todas las dependencias necesarias para construir esta aplicación.
Ahora, para crear una aplicación React simple, necesitamos dos bibliotecas principales: React y ReactDOM. Así que vamos a agregarlos como dependencias a nuestra aplicación usando npm.
$ npm i react react-dom --save
A continuación, debemos agregar un paquete web, para que podamos agrupar nuestra aplicación. No solo el paquete, sino que también necesitaremos una recarga en caliente que es posible usando el servidor de desarrollo webpack.
$ npm i webpack webpack-dev-server webpack-cli --save--dev
El --save--dev
es especificar que estos módulos son solo dependencias de desarrollo. Ahora que estamos trabajando con React, debemos tener en cuenta que React usa clases de ES6 y declaraciones de importación, algo que quizás no todos los navegadores puedan entender. Para asegurarnos de que el código sea legible por todos los navegadores, necesitamos una herramienta como babel para transpilar nuestro código al código legible normal para los navegadores.
$ npm i babel-core babel-loader @babel/preset-react @babel/preset-env html-webpack-plugin --save-dev
Bueno, ¿qué puedo decir? Ese fue el número máximo de instalaciones que prometo. En el caso de babel, hemos cargado primero la biblioteca principal de babel, luego el cargador y finalmente 2 complementos o ajustes preestablecidos para trabajar específicamente con React y todo el nuevo código ES2015 y ES6 en adelante.
Continuando, agreguemos algo de código y comencemos la configuración del paquete web.
Así es como debería verse el archivo package.json después de todas las instalaciones hasta ahora. Es posible que tenga un número de versión diferente dependiendo de cuándo esté siguiendo este artículo.
El código
Comencemos agregando un archivo webpack.config.js en la raíz de la estructura de nuestra aplicación. Agregue el siguiente código en su archivo webpack.config.
const path = require('path');const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = { //This property defines where the application starts entry:'./src/index.js',
//This property defines the file path and the file name which will be used for deploying the bundled file output:{ path: path.join(__dirname, '/dist'), filename: 'bundle.js' },
//Setup loaders module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: 'babel-loader' } } ] },
// Setup plugin to use a HTML file for serving bundled js files plugins: [ new HtmlWebpackPlugin({ template: './src/index.html' }) ]}
Bien, entendamos las líneas de arriba.
Primero comenzamos solicitando que el módulo de ruta predeterminado acceda a la ubicación del archivo y realice cambios en la ubicación del archivo.
A continuación, necesitamos HTMLWebpackPlugin para generar un archivo HTML que se utilizará para servir archivos / archivos JavaScript incluidos. Lea más sobre HTMLWebpackPlugin haciendo clic en el enlace.
Luego tenemos el objeto export.module con algunas propiedades en ellos. La primera es la propiedad de entrada,which is used to specify which file webpack should start with to get the internal dependency graph created.
module.exports = {
entry:'./src/index.js'
}
Next up is the output property specifying where the bundled file should be generated and what the name of the bundled file would be. This is done by the output.path and output.filename properties.
module.exports = {
//This property defines the file path and the file name which will be used for deploying the bundled file output:{ path: path.join(__dirname, '/dist'), filename: 'bundle.js' },
}
Next up are the loaders. This is to specify what webpack should do for a specific type for file. Remember that webpack out of box only understands JavaScript and JSON, but if your project has any other language used, this would be the place to specify what to do with that new language.
module.exports = {
//Setup loaders module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: 'babel-loader' } } ] }
}
The information should be specified in an object for each module property, which further has an array of rules. There will be an object for every case. I have also specified to exclude everything in my node_modules folder.
Next up is the plugin property. This is used to extend the capabilities of webpack. Before a plugin can be used in the plugin array inside the module exports object, we need to require the same.
module.exports = {
// Setup plugin to use a HTML file for serving bundled js files plugins: [ new HtmlWebpackPlugin({ template: './src/index.html' }) ]
}
This particular plugin, as explained earlier, will use the specified file in our src folder. It’ll then use that as a template for our HTML file where all the bundled files will be automatically injected. There are a lot of other out of the box plugins that we could use — checkout the official page for more information.
The last thing we need to do is create a .babelrc file to use the babel preset we installed and take care of the ES6 classes and import statements in our code. Add the following lines of code to the .babelrc file.
{ "presets": ["env", "react"]}
And just like that, now babel will be able to use those presets. Okay so enough of the setup — let’s add some React code to see how this works.
React Code
Since the starting point for the application is the index.js file in src folder, let’s start with that. We will start by requiring both React and ReactDOM for our use in this case. Add the below code in your index.js file.
import React from 'react';import ReactDOM from 'react-dom';import App from './Components/App';
ReactDOM.render(, document.getElementById('app'));
So we simply import another file from our components folder, which you will create, and add another file in the folder called App.js. So let’s see what’s inside the App.js file:
import React, { Component } from 'react'
class App extends Component { render() { return ( Webpack + React setup
) }}
export default App;
We are almost done. The only thing left now is to enable hot reloading. This means that every time a change is detected, the browser auto reloads the page and has the ability to build and bundle the entire application when the time comes.
We can do this by adding script values in the package.json file. Remove the test property in the scripts object of your package.json file and add these two scripts:
"start": "webpack-dev-server --mode development --open --hot",
"build": "webpack --mode production"
You are all set! Go to your terminal, navigate to the root folder, and run npm start. It should start a dev server on your computer and serve the HTML file in your browser. If you make any minor/major changes and save the code, your browser will be automatically refreshed to show the latest set of changes.
Once you think you are ready to get the app bundled, you just need to hit the command, npm build, and webpack will create an optimised bundle in your project folder which can be deployed on any web server.
Conclusion
This is just a small application or use case of webpack and babel, but the applications are limitless. I hope you are excited enough to explore more options and ways of doing things with webpack and babel. Please refer to their official websites to know more and read in depth.
I have created a Github repo with all the code in it, so please refer to it incase of any questions.
ashishcodes4/webpack-react-setup
Setting a react application from scratch without using CLI - ashishcodes4/webpack-react-setupgithub.com
My two cents about webpack? Well, at times you may think that it’s nothing more than a tool, and why should you bother too much for a tool? But trust me when I say this: the initial struggle while learning your way around webpack will save you an enormous number of hours you would otherwise invest developing without webpack.
That’s all for now, hope to be back with yet another interesting article very soon. I hope you have enjoyed reading this one!
In case you face any difficulty or issues while following any of the above mentioned steps/processes, please feel free to get in touch and leave comments.
LinkedIn: //www.linkedin.com/in/ashish-nandan-singh-490987130/
Twitter: //twitter.com/ashishnandansin