You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

2 Días
12 Hrs
11 Min
53 Seg

Migracion de Webpack 4 a Webpack 5

7/22
Resources

How to upgrade a project to Webpack 5 and React 17?

Upgrading your project to the latest versions of tools and libraries is crucial to keep it efficient and secure. In this case, we will explore the process of upgrading a project using Webpack 5 and React 17 to optimize its performance and features. Let's talk about the Platzi Store project, with which we will perform the upgrade.

What is Platzi Store and how to configure it?

Platzi Store is a project used in several courses to learn about unit testing, tools like Webpack, and other advanced development concepts. The first thing to do is to access this project through a clone or fork from its repository, which you can find in the links section of the course.

  1. Clone the project: Use the command git clone URL where URL is the address of the Platzi Store repository.
  2. Access the project folder: Open the terminal and navigate to the folder with cd platzi-store.
  3. Open the project in an editor: You can use Visual Studio Code or any editor of your choice with code . to open the project.

How to review and understand the current configuration of the project?

Before making any updates, it is essential to understand how the project is currently configured:

  • Important files: Check the README.md for basic instructions and the package.json file to understand the dependencies and scripts that run.
  • Webpack configurations: This file defines entry and exit points, extensions to work with (such as .js and . jsx), loaders and plugins that optimize and process the project.

What needs to be updated in Webpack and React?

Below, you'll see which dependencies you need to upgrade to take advantage of the latest features:

  1. Webpack: Upgrading to Webpack 5 is essential, along with its CLI and various plugins.
  2. React: Moving to React 17 and its associated libraries, such as react-dom and react-redux, is also paramount.

How to upgrade Webpack and its components?

To make sure everything is updated to the latest versions, run the following commands in the terminal:

npm install webpack@latest webpack-cli@latest babel-loader@latest webpack-plugin@latest mini-css-extract-plugin@latest

This will ensure you have the latest versions and resolve any incompatibilities.

How to update React and its related dependencies?

Similarly, perform the React upgrade by running:

npm install react@latest react-dom@latest react-router@latest react-redux@latest redux@latest redux@latest

What steps to follow after the update?

Once the dependencies have been updated, make sure to configure Webpack correctly for local development. In Webpack 5, the use of webpack-dev-server has changed, now you should simply use webpack serve.

How to check that everything works correctly?

Finally, run the project to verify that everything is in order:

npm run start

This command will compile your project and open the browser on the port configured for local development, allowing you to view and test your updated application. This is a good time to test thoroughly and verify that there are no errors in Redux's built-in paths or state systems.

With the project now updated and running properly, we are ready to further optimize and continue exploring best practices in modern development - keep learning and improving your skills!

Contributions 14

Questions 1

Sort by:

Want to see more contributions, questions and answers from the community?

Cambios en React-router-dom

Como sabemos hemos actualizado la mayoria de nuestras dependencias en el proyecto de Platzi Store, lo cual conlleva a analizar si se han realizado ciertos cambios.

El cambio mas notorio es que Switch ya no es un modulo exportado de react-router-dom y ha sido remplazado por Routes en la nueva version

Ademas de unos cambios pequeños a la hora de definir las rutas de la app

Cambiando de esto:

<Route exact path='/' component={Home} />

A esto :

<Route exact path='/' element={<Home />} />

y para definir el default de la ruta en caso del notFount usaremos el path *

<Route path ='*' element={<NotFound />} />

Si es que alguien obtiene un error como:
Attempted import error: 'Switch' is not exported from 'react-router-dom'

Chequen:
https://stackoverflow.com/questions/63124161

Migracion de Webpack 4 a Webpack

Después de tener ya el proyecto en nuestro entorno de desarrollo.

  • Actualizamos.
    Webpack y plugins:
npm install webpack@latest webpack-cli@latest babel-loader@latest html-webpack-plugin@latest mini-css-extract-plugin@latest

React:

npm install react@latest react-dom@latest react-router-dom@latest react-redux@latest redux@latest 

y npm install
Importante: en package.json:
Cambiamos:

"start": "webpack-dev-server --open --mode development",

Cambió, desde webpack 5 ya es:

"start": "webpack serve --open --mode development",

y npm run start

Para la nueva version de React (18 al crear este comentario) se debe actualizar el index.js. Porque con react 18 se cambio la forma de iniciar el root para el React app

Tienes que cambiar a esto:

const container = document.getElementById('app');
const root = ReactDOM.createRoot(container);
root.render(
  <Provider store={store}>
    <App />
  </Provider>
);

Aun no entiendo bien React pero a la fecha de hoy no me funcionó y viendo los aportes entiendo que algo se actualizó. Lo que se encarga de las rutas cambió por esa razón debe modificar en App.jsx Switch por Routes:

import React from 'react';
import { BrowserRouter, Routes, Route } from 'react-router-dom';

import Home from '../containers/Home';
import Checkout from '../containers/Checkout';
import Layout from '../components/Layout';
import NotFound from '../containers/NotFound';

const App = () => (
  <BrowserRouter>
    <Layout>
      <Routes>
        <Route exact path='/' element={<Home />} />
        <Route exact path='/checkout' element={<Checkout />} />
        <Route path='*' element={<NotFound />} />
      </Routes>
    </Layout>
  </BrowserRouter>
);

export default App;

Para esta fecha donde estamos usando React 18, React Router Dom 6, React-redux 8, Webpack 5, etc…
Para poder avanzar en esta clase, y recopilando las soluciones que leí de los otros compañeros, este es el paso a paso para lograr que el proyecto funcione.

  1. Primero cambiar la forma de importar, y llamar dependencias en el index.js:
import ReactDOM from 'react-dom/client';
import { legacy_createStore as createStore } from 'redux';
  1. Instalar la última versión del Webpack dev server:
npm i webpack-dev-server@latest
  1. Cambiar el Switch por Routes en el archivo de App.jsx donde se listan las rutas de la aplicación

Si tienen problemas con webpack-cli cuadno hace npm start
deben instalar la ultima version de webpack-dev-server

npm i webpack-dev-server@latest

Haciendo Fork al Proyecto

1.- En Github le haces Fork ( clickeas el icon del fork)

2.- git clone https://github.com/gndx/platzi-store ó la url de tu fork.
Pd: No hace falta hacer git reset “id-del-commit”, porque el profesor en el branch master esta con el commit de esta clase. y hay otro branch con los commit de clases posteriores llamado clase/10

  • Pero por si tienen algún problema:
    3.- Para que regresen en el tiempo a el commit de esta clase:
git reset --hard  974426a

y listo

Se generó al compilar el proyecto debido a que no se instauro la configuración de babel para soportar jsx. Lo solucioné actualizando todo lo relacionado a babel y creando el fichero de configuración de .babelrc

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

Para los que usan wsl2 y no les muestra nada en localhost:3000, pueden reiniciar wsl con el comando en powershell de windows

wsl --shutdown 

o pueden también intentar con una configuración en webpack y buscar la ip de su wsl colocando ipconfig en el cmd o powershell de windows y tomando la ipv4 de wsl y colocándola en su navegador. esto con el fin de que dev-server acepte conexiones externas.

devServer: {
    host: '0.0.0.0',
  },

si no les sale completo la platzi store y solo les sale el navbar y el footer tienen que modificar las rutas en el archivo app.js para que tome las nuevas configuraciones de react-router-dom V6

<Switch> -> <Routes>
component -> element
ej:
<Routes>
<Route exact path="/" element={<Home/>}>
<Routes/>

Si manejan Yarn les dejo este comnando asi actualizan todo a la vez

 yarn upgrade-interactive --latest 

la propiedad externals lo que hace es excluir paquetes del bundle final.

Les recomiendo la extensión version lens para vsc, cuando la instalan van al package.json, le dan al icono superior derecho de la V que es de la extensión y les mostrará todas las dependencias que están desactualizadas, o si están en su versión más reciente y desde ahí mismo las pueden actualizar a la más segura (LTS) o a la más reciente.