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
9 Hrs
52 Min
7 Seg

Code Splitting en desarrollo

17/22
Resources

How to split a React application into separate components using Webpack?

The key to keeping a React project scalable is to split it into modular components. This not only improves organization, but also makes it easier to work independently on various parts of the project. We can leverage tools like Webpack to handle multiple applications efficiently. Next, I'll show you how to structure our applications using this approach.

What is necessary to get started?

Before taking the steps, it is vital to understand some basic concepts:

  • Micro Frontends: This methodology allows you to create pieces of the user interface divided into smaller applications that work independently.
  • Webpack: It is an essential tool for packaging JavaScript modules and helps us to manage different configurations.

How to configure a header as a separate application?

  1. Create a separate application folder:
    • In our project, inside the src folder, we create a new one called header.
  2. Organize the files inside the new folder:
    • In header, we add an index.js file as the entry point of the application.
    • We create a subfolder components inside header and an App.jsx file for our main component.
// index.jsimport React from 'react';import ReactDOM from 'react-dom';import App from './components/App';
ReactDOM.render(<App/>, document.getElementById('header'));
// components/App.jsximport React from 'react';
const App = () => <div>Hello React from Header</div>;
export default App;
  1. Modify the HTML file to include the new div:
    • Add a new <div id="header"></div> in the public/index.html where our header application will be mounted.

How do we configure Webpack to handle multiple inputs?

  1. Update input configuration:
    • In the Webpack configuration file, we define multiple entry points.
// webpack.config.jsmodule.exports = { entry: { home: './src/index.js', header: './src/header/index.js' }, output: { filename: '[name].bundle.js', path: __dirname + '/dist' } };
  1. Configuration for chunking and optimization:
    • Make sure Webpack correctly chunks resources using chunkFilename.

How to verify if the configuration is correct?

To verify that everything is correctly configured, we will follow these steps:

  1. Initialize the development environment:
    • Run the npm run start command in the terminal to activate the development server.
  2. Inspect elements in the browser:
    • Using developer tools in the browser, verify that components render as expected. Look for elements such as Hello React from Header and make sure they are loaded from separate bundles.

This methodology not only ensures a solid project structure, but also allows different teams to work in parallel without conflicts. Keep exploring new techniques and methods to improve your workflows with React and Webpack!

Contributions 4

Questions 3

Sort by:

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

Code Splitting en desarrollo

Existe una clase del curso de Optimizaci贸n web que lo explica: clase.
Podemos ver que el code splitting es dividir el c贸digo, es beneficioso el uso que se le quiera dar, ya que se puede implementar de diferentes formas.
-------------- 驴Qu茅 hicimos en esta clase? ------------
1.- Creamos una carpeta Header dentro de src.
2.- Creamos dentro de Header:
- Un Archivo llamado index.js
- Una carpeta llamada components.
- Dentro de esa carpeta components se crea el archivo App.jsx
3.- en src/Header/components/App.jsx:

import React from 'react';

const App = () => {
    return (
        <h1>Hello React From Header</h1>
    );
}

export default App;

4.- en src/Header/index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App';


ReactDOM.render(<App />, document.getElementById('header'));

5.- en public > index.html:
A帽adimos e div con id : header

  <body>
    <div id="header"></div>
    <div id="app"></div>
  </body>
  • En webpack.config.dev.js:
    Modificamos entry y output:
module.exports = {
  entry: {
    home: './src/index.js',
    header: './src/Header/index,js',
  },
 .....
},
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].bundle.js',
    chunkFilename: '[name].bundle.js',
  },

y npm run start

por fin alguien habla de micro frontends. Module federation es una feature interesante de webpack para los micro frontends.

si tienen instalada la extension de snippets de react (ES7+ React/Redux/React-Native snippets) solo escriban rafce y enter, o tab para que se cree algo asi:

import React from 'react'

const App = () => {
  return (
    <div>App</div>
  )
}

export default App

en este caso aparece const App, <div>App</div> y export default App porque mi achivo se llama App.jsx, la extensi贸n reemplaza automaticamente ese valor seg煤n el nombre de tu archivo.

hola gente. estoy en b煤squeda de los mejores recursos para hacer codesplitting desde webpack. Si tienes alguno d茅jalo aqu铆 pls. en otras noticias, al parecer React.lazy y React.Suspense hacen code splitting manteniendo vac铆os los espacios hasta que son requeridos o: Es decir es Code Splitting desde React. Puedes cumplir el reto usando los pero a m铆 me interesa saber hacerlo desde webpack tambi茅n. C贸mo lo hace Oscar me genera muchos problemas, m谩s que nada en el la conexi贸n del estado y del router. Tambi茅n si recomiendan links de MicroFrontends estar铆a genial porque ese concepto y modo de trabajo no lo comprendo completamente.