Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 35 additions & 34 deletions version 4/05 Misc/07 Webpack Lazy Loading/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,37 +36,25 @@ npm install --save-dev @babel/plugin-syntax-dynamic-import

It automatically adds that entry to our _package.json_.

_package.json_
### ./package.json

```diff
"devDependencies": {
"@babel/core": "^7.1.0",
+ "@babel/plugin-syntax-dynamic-import": "^7.0.0",
"@babel/preset-env": "^7.1.0",
"babel-loader": "^8.0.2",
"@babel/cli": "^7.2.3",
"@babel/core": "^7.3.4",
+ "@babel/plugin-syntax-dynamic-import": "^7.2.0",
"@babel/preset-env": "^7.3.4",
"babel-loader": "^8.0.5",
"html-webpack-plugin": "^3.2.0",
"webpack": "^4.19.1",
"webpack-cli": "^3.1.1",
"webpack-dev-server": "^3.1.8"
"webpack": "^4.29.6",
"webpack-cli": "^3.2.3",
"webpack-dev-server": "^3.2.1"
},
```

- First we will create the .babelrc config file on the root with the next content:
- Now we will configure the babel plugin syntax dynamic import at the plugin section of the _.babelrc_ file:

```diff
+ {
+ "presets": [
+ [
+ "@babel/preset-env",
+ {
+ "useBuiltIns": "entry"
+ }
+ ]
+ ]
+ }
```

- Now we will configure the babel plugin syntax dynamic import at the plugin section of the .babelrc file:
### ./.babelrc

```diff
{
Expand All @@ -84,15 +72,22 @@ _package.json_

- Now it's ready to be used. Just to test it, let's change the synchronous import on the students.js file. Let's import the averageService module lazily when button clicked.

_lazy loading the averageService module:_
### ./students.js

> import(/\* webpackChunkName "averageService" \*/ "./averageService").then(...)

Steps:
```diff
- import {getAvg} from "./averageService";
$('body').css('background-color', 'lightSkyBlue');
- const scores = [90, 75, 60, 99, 94, 30];
- const averageScore = getAvg(scores);
- const messageToDisplay = `average score ${averageScore}`;
- document.write(messageToDisplay);
```

- Create getComponent function load the averageService module lazily, and return div element async with the average score:

```diff
$('body').css('background-color', 'lightSkyBlue');

+ const getComponent = () =>
+ import(/* webpackChunkName "averageService" */ "./averageService").then(
+ averageServiceModule => {
Expand All @@ -111,16 +106,18 @@ Steps:
- Create handleOnClick function will call the getComponent function and append the average score to container:

```diff
...
+ const handleOnClick = () => {
+ getComponent().then(element =>
+ document.getElementById("container").append(element)
+ );
};
+ };
```

- Create a button to handle on click event and load the average score:

```diff
...
+ const button = document.createElement("button");
+ button.innerText = "Lazy loading sample";
+ button.onclick = handleOnClick;
Expand All @@ -129,12 +126,11 @@ Steps:

Then, our _students.js_ file look like this:

_./students.js_
### ./students.js

```
$("body").css("background-color", "lightSkyBlue");

// getComponent function load the averageService module lazily, and return div element async with the average score:
const getComponent = () =>
import(/* webpackChunkName "averageService" */ "./averageService").then(
averageServiceModule => {
Expand All @@ -149,24 +145,22 @@ const getComponent = () =>
}
);

// handleOnClick function will call the getComponent function and append the average score to container:
const handleOnClick = () => {
getComponent().then(element =>
document.getElementById("container").append(element)
);
};

// Create a button to handle on click event and load the average score:
const button = document.createElement("button");
button.innerText = "Lazy loading sample";
button.onclick = handleOnClick;
document.getElementById("container").append(button);

```

- Finally we need add the container div into index.html:
- Finally we need to add the _div_ container in _index.html_:

_./index.html_
### ./index.html

```diff

Expand All @@ -193,3 +187,10 @@ _./index.html_
```bash
npm start
```

# About Lemoncode

We are a team of long-term experienced freelance developers, established as a group in 2010.
We specialize in Front End technologies and .NET. [Click here](http://lemoncode.net/services/en/#en-home) to get more info about us.

For the LATAM/Spanish audience we are running an Online Front End Master degree, more info: http://lemoncode.net/master-frontend
196 changes: 196 additions & 0 deletions version 4/05 Misc/07 Webpack Lazy Loading/README_es.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,196 @@
# 06 Lazy Loading

En este ejemplo cargaremos paquetes de forma asíncrona a través de npm.

Partiremos del ejemplo _00 intro/05 jquery_.

Pasos resumidos:

- Requisitos previos:
- Los paquetes nodejs deben estar instalados
- (Opcional) punto de partida _00 intro/05 jquery_
- Instalar el paquete @babel/plugin-syntax-dynamic-import a través de npm
- Configurar el fichero de configuración de Babel (_.babelrc_)
- Cambiar la importación sincrónica del módulo en students.js y cargar el módulo averageService de forma diferida (_lazy loading_).
- Añadir el contenedor div en index.html

# Pasos para realizarlo

## Requisitos previos

Necesitará tener _nodejs_ instalado (al menos v 8.9.2) en su ordenador. Si desea seguir los pasos de esta guía, deberá tomar como punto de partida el ejemplo _00 intro/05 jquery_.

## Pasos

- `npm install` para instalar los paquetes del ejemplo anterior:

```bash
npm install
```

- Empecemos por descargar la biblioteca _@babel/plugin-syntax-dynamic-import_ a través de npm. En este caso ejecutaremos el siguiente comando en la línea de comandos: `npm install --save-dev @babel/plugin-syntax-dynamic-import`.

```
npm install --save-dev @babel/plugin-syntax-dynamic-import
```

Esto añade automáticamente esa entrada a nuestro _package.json_.

### ./package.json

```diff
"devDependencies": {
"@babel/cli": "^7.2.3",
"@babel/core": "^7.3.4",
+ "@babel/plugin-syntax-dynamic-import": "^7.2.0",
"@babel/preset-env": "^7.3.4",
"babel-loader": "^8.0.5",
"html-webpack-plugin": "^3.2.0",
"webpack": "^4.29.6",
"webpack-cli": "^3.2.3",
"webpack-dev-server": "^3.2.1"
},
```

- Ahora configuraremos la importación dinámica en la sección de plugins del archivo _.babelrc_:

### ./.babelrc

```diff
{
"presets": [
[
"@babel/preset-env",
{
"useBuiltIns": "entry"
}
]
],
+ "plugins": ["@babel/plugin-syntax-dynamic-import"]
}
```

- Ahora está listo para ser usado. Sólo para probarlo, cambiemos la importación sincrónica en el archivo _students.js_. Importemos el módulo _averageService_ de forma diferida cuando se pulse el botón.

### ./students.js

```diff
- import {getAvg} from "./averageService";
$('body').css('background-color', 'lightSkyBlue');
- const scores = [90, 75, 60, 99, 94, 30];
- const averageScore = getAvg(scores);
- const messageToDisplay = `average score ${averageScore}`;
- document.write(messageToDisplay);
```

- Creamos la función _getComponent_, cargamos el módulo _averageService_ de forma diferida y devolvemos el elemento div de forma asíncrona con la puntuación media:

```diff
$('body').css('background-color', 'lightSkyBlue');

+ const getComponent = () =>
+ import(/* webpackChunkName "averageService" */ "./averageService").then(
+ averageServiceModule => {
+ const scores = [90, 75, 60, 99, 94, 30];
+ const averageScore = averageServiceModule.getAvg(scores);
+ const messageToDisplay = `average score ${averageScore}`;
+
+ const element = document.createElement("div");
+ element.innerText = messageToDisplay;
+
+ return element;
+ }
+ );
```

- La función _handleOnClick_ llamará a la función _getComponent_ y añadirá la puntuación media al contenedor:

```diff
...
+ const handleOnClick = () => {
+ getComponent().then(element =>
+ document.getElementById("container").append(element)
+ );
+ };
```

- Creamos un botón para manejar el evento de click y cargar la puntuación media:

```diff
...
+ const button = document.createElement("button");
+ button.innerText = "Lazy loading sample";
+ button.onclick = handleOnClick;
+ document.getElementById("container").append(button);
```

Ahora, nuestro archivo _students.js_ tiene este aspecto:

### ./students.js

```
$("body").css("background-color", "lightSkyBlue");

const getComponent = () =>
import(/* webpackChunkName "averageService" */ "./averageService").then(
averageServiceModule => {
const scores = [90, 75, 60, 99, 94, 30];
const averageScore = averageServiceModule.getAvg(scores);
const messageToDisplay = `average score ${averageScore}`;

const element = document.createElement("div");
element.innerText = messageToDisplay;

return element;
}
);

const handleOnClick = () => {
getComponent().then(element =>
document.getElementById("container").append(element)
);
};

const button = document.createElement("button");
button.innerText = "Lazy loading sample";
button.onclick = handleOnClick;
document.getElementById("container").append(button);

```

- Finalmente necesitamos añadir el contenedor _div_ en _index.html_:

### ./index.html

```diff

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Webpack 4.x by sample</title>
</head>
<body>
Hello Webpack 4!
+ <div id="container"></div>
</body>
</html>

```

## Ejecutando y Probando

- Ahora podemos simplemente ejecutar la aplicación (`npm start`) y comprobar cómo se carga el paquete _averageService_ al pulsar el botón _Lazy loading sample_ (comprobándolo en la pestaña _network_ de las herramientas de desarrollo del navegador).

```bash
npm start
```

# About Lemoncode

We are a team of long-term experienced freelance developers, established as a group in 2010.
We specialize in Front End technologies and .NET. [Click here](http://lemoncode.net/services/en/#en-home) to get more info about us.

For the LATAM/Spanish audience we are running an Online Front End Master degree, more info: http://lemoncode.net/master-frontend