Skip to content
Merged
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
7 changes: 0 additions & 7 deletions 04-frameworks/01-react/03-react-hooks/00-boilerplate/.babelrc

This file was deleted.

131 changes: 11 additions & 120 deletions 04-frameworks/01-react/03-react-hooks/00-boilerplate/Readme.md
Original file line number Diff line number Diff line change
@@ -1,125 +1,16 @@
# 03 Webpack React
# 02 Vite boiler plate - React

## Summary

This example takes the _02-webpack-boiler_ example as a starting point.

We will go step by step adding the necessary configuration so that we integrate
**React** into our build process.

# Step by Step guide

- First we copy the previous example, and do a _npm install_

```bash
npm install
```

- Let's install _react_ and _react-dom_

```bash
npm install react react-dom --save
```

- Let's install _react_ and _react-dom_ typings

```bash
npm install @types/react @types/react-dom --save-dev
```

This way we have the React library and the bindings to integrate with a web browser.

- In the index.html we are going to put the _div_ that will serve as entry point to instantiate our React application. our React application.

_./src/index.html_

```diff
<body>
- <h1 class="my-text">Hello World !</h1>
+ <div id="root"></div>
</body>
```

- Let's create our first React component.

_./src/app.tsx_

```tsx
import React from "react";

export const App = () => {
return <h1>Hello React !!</h1>;
};
```

- It's time to instantiate that main component, to be able to integrate it with the browser we have to make use of _ReactDOM.render_.

_./src/index.tsx_

```tsx
import React from "react";
import ReactDOM from "react-dom";
import { App } from "./app";

ReactDOM.render(
<div>
<App />
</div>,
document.getElementById("root")
);
```

- We are on the right track, but if we try to run this it will fail, since _babel_ does not know how to transform the _jsx_ (remember that this was a sugar, which was actually an XML) into javaScript, in order for babel to be able to understand this we have to install the _preset_ _@babel/preset-react_

First we install it and the configure it.

```bash
npm install @babel/preset-react --save-dev
```

_.babelrc_

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

> By the way the _rc_ suffix is pretty usual in linux it's stands for "runcom"
> (CTSS system 1962-63) Script file containing startup instructions for an application program.
> In other words, "rc" is just something that stuck from back in the sixties, and has been used quite often for configuration files in different sorts of programs since, including Node, Babel and many, many others.
> More info [on stackoverflow](https://stackoverflow.com/questions/36212256/what-are-rc-files-in-nodejs).

> Another curiosity... what is a _preset_ ... let's start with what is a babel plugin: babel transformations are
> enabled by applying plugins, there are plenty of plugins and if you have to go adding one by one it can become a nightmare,
> in order to make this easier, babel has grouped common sets of plugins in _presets_, for instance @babel-preset-react
> includes the following plugins:

- @babel/plugin-syntax-jsx
- @babel/plugin-transform-react-jsx
- @babel/plugin-transform-react-display-name

- Is time to double check the _webpack.config.js_

- We can make sure that we have _ts_ and _tsx_ as valid extensions.
- Also that in the loader we accept both _ts_ and _tsx_.
- And in the app we have as entry point _index.tsx_.

* Let's check that things are working as expected:

```bash
npm start
```







Boiler plate extracted from _02-base/02-vite-react_.

Below, main points. For more info, check the original repo or the Vite module.

- Installation of `typeScript` as a local development dependency.
- Installation of `@vitejs/plugin-react` as a local development dependency (support for `jsx` and `tsx`).
- Installation of `react` and `react-dom` as dependencies.
- Installation of the types `@types/react` and `@types/react-dom` as local development dependencies.
- The project was changed to use ES Modules `package.json`.
- A `tsconfig.json` was created with a minimal configuration, prepared to support `jsx` format.
- Vite uses esbuild for transpilation (fast, no type checking).
- `isolatedModules` and `useDefineForClassFields` were enabled to be compatible with `esbuild`.
125 changes: 11 additions & 114 deletions 04-frameworks/01-react/03-react-hooks/00-boilerplate/Readme_es.md
Original file line number Diff line number Diff line change
@@ -1,119 +1,16 @@
# 03 Webpack React
# 02 Vite boiler plate - React

## Resumen

Este ejemplo toma como punto de partida el ejemplo _02-webpack-boiler_.
Boiler plate extraído de _02-base/02-vite-react_.

Vamos a ir paso a paso añdiendo la configuración necesaria para que integrar
**React** en nuestro proceso de build.
A continuación, puntos principales. Para más info, acudir a repo original o módulo de vite.

## Paso a Paso

- Primero copiamos el ejemplo anterior, y hacemos un _npm install_

```bash
npm install
```

- Vamos a instalar _react_ y _react-dom_

```bash
npm install react react-dom --save
```

- Vamos a instalarnos los typing de _react_ y _react-dom_

```bash
npm install @types/react @types/react-dom --save-dev
```

Así tenemos la librería de React y los bindings para que se integre con un navegador web.

- En el index.html vamos a meter el _div_ que nos servirá como punto de entrada para instanciar
nuestra aplicación React.

_./src/index.html_

```diff
<body>
- <h1 class="my-text">Hello World !</h1>
+ <div id="root"></div>
</body>
```

- Vamos a crear nuestro primero componente React.

_./src/app.tsx_

```tsx
import React from "react";

export const App = () => {
return <h1>Hello React !!</h1>;
};
```

- Es hora de instanciar ese compente principal, para poder integrarlo con el navegador
tenemos que hacer uso a _ReactDOM.render_

_./src/index.tsx_

```tsx
import React from "react";
import { createRoot } from "react-dom/client";
import { App } from "./app";

const container = document.getElementById("root");
const root = createRoot(container);

root.render(<App />);
```

- Vamos por buen camino, pero si intentamos ejecutar esto no va fallar, ya que _babel_ no sabe
como transformar el _jsx_ (recordemos que esto era un azúcar, que en realidad era un XML) a
javaScript, para que babel sea capaz de entender esto tenemos que instalar el _preset_
_@babel/preset-react_

Primero lo instalamos

```bash
npm install @babel/preset-react --save-dev
```

_.babelrc_

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

> Por cierto, el sufijo _rc_ es bastante habitual en linux, significa "runcom".
> (Sistema CTSS 1962-63) Archivo de script que contiene instrucciones de inicio para un programa de aplicación.
> En otras palabras, "rc" es algo que se quedó atrás en los años sesenta, y se ha utilizado con bastante frecuencia para los archivos de configuración en diferentes tipos de programas desde entonces, incluyendo Node, Babel y muchos, muchos otros.
> Más información [en stackoverflow](https://stackoverflow.com/questions/36212256/what-are-rc-files-in-nodejs).

> Otra curiosidad... qué es un _preset_ ... empecemos por lo que es un plugin de babel: las transformaciones de babel
> se habilitan aplicando plugins, hay un montón de plugins y si tienes que ir añadiendo uno a uno se puede convertir en una pesadilla,
> para hacer esto más fácil, babel ha agrupado conjuntos comunes de plugins en _presets_, por ejemplo @babel-preset-react
> incluye los siguientes plugins:

- @babel/plugin-syntax-jsx
- @babel/plugin-transform-react-jsx
- @babel/plugin-transform-react-display-name

- Es hora de saltar al _webpack.config.js_

- Nos podemos asegurar de que tenemos como extension valida _ts_ y _tsx_
- También que en el loader aceptamos tanto _ts_ como _tsx_
- Y en el app tenemos como punto de entrada _index.tsx_

* Vamos a comprobar que hemos dejado todo funcionando:

```bash
npm start
```
- Instalación de `typeScript` como dependencia de desarrollo local.
- Instalación de `@vitejs/plugin-react` como dependencia de desarrollo local (soporte `jsx` y `tsx`)
- Instalación de `react` y `react-dom` como dependencias.
- Instalación de los tipos de `@types/react` y `@types/react-dom` como dependencia de desarrollo local.
- Se cambió el proyecto para usar ES Modules `package.json`.
- Se creó un `tsconfig.json` con una configuración mínima, preparada para soportar formato `jsx`.
- Vite utiliza esbuild para la transpilación (rápido, sin comprobación de tipos).
- Se habilitó `isolatedModules` y `useDefineForClassFields` para que sea compatible con `esbuild`.
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
<!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>My App Example</title>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>React App - React hooks</title>
</head>

<body>
<div id="root"></div>
<script type="module" src="/src/index.tsx"></script>
</body>
</html>
46 changes: 15 additions & 31 deletions 04-frameworks/01-react/03-react-hooks/00-boilerplate/package.json
Original file line number Diff line number Diff line change
@@ -1,39 +1,23 @@
{
"name": "react-example",
"version": "1.0.0",
"description": "",
"main": "index.js",
"name": "hello-vite",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"start": "run-p -l type-check:watch start:dev",
"type-check": "tsc --noEmit",
"type-check:watch": "npm run type-check -- --watch",
"start:dev": "webpack-dev-server --mode development --open",
"build": "rimraf dist && webpack --mode development"
"start": "vite --host",
"build": "vite build",
"preview": "vite preview"
},
"author": "",
"license": "ISC",
"devDependencies": {
"@babel/cli": "^7.17.10",
"@babel/core": "^7.17.10",
"@babel/preset-env": "^7.17.10",
"@babel/preset-react": "^7.17.12",
"@babel/preset-typescript": "^7.16.7",
"@types/react": "^18.0.9",
"@types/react-dom": "^18.0.4",
"babel-loader": "^8.2.5",
"css-loader": "^6.7.1",
"html-loader": "^3.1.0",
"html-webpack-plugin": "^5.5.0",
"npm-run-all": "^4.1.5",
"rimraf": "^3.0.2",
"style-loader": "^3.3.1",
"typescript": "^4.6.4",
"webpack": "^5.72.1",
"webpack-cli": "^4.9.2",
"webpack-dev-server": "^4.9.0"
"@types/react": "^19.1.8",
"@types/react-dom": "^19.1.6",
"@vitejs/plugin-react": "^4.6.0",
"typescript": "^5.8.3",
"vite": "^7.0.4",
"vite-plugin-checker": "^0.10.0"
},
"dependencies": {
"react": "^18.1.0",
"react-dom": "^18.1.0"
"react": "^19.1.0",
"react-dom": "^19.1.0"
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import React from "react";
import { createRoot } from "react-dom/client";
import { App } from "./app";

const container = document.getElementById("root");
const root = createRoot(container);
const rootElement = document.getElementById("root");
const root = createRoot(rootElement);

root.render(<App />);
25 changes: 13 additions & 12 deletions 04-frameworks/01-react/03-react-hooks/00-boilerplate/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,18 +1,19 @@
{
"compilerOptions": {
"target": "es6",
"module": "es6",
"moduleResolution": "node",
"declaration": false,
"esModuleInterop": true,
"isolatedModules": true,
"jsx": "react-jsx",
"lib": ["ESNext", "DOM"],
"module": "ESNext",
"moduleResolution": "bundler",
"noEmit": true,
"noImplicitAny": false,
"allowSyntheticDefaultImports": true,
"sourceMap": true,
"jsx": "react",
"noLib": false,
"suppressImplicitAnyIndexErrors": true,
"noImplicitReturns": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"esModuleInterop": true
"sourceMap": true,
"target": "ESNext",
"useDefineForClassFields": true
},
"include": ["src/**/*"],
"exclude": ["node_modules"]
"include": ["src"]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { defineConfig } from "vite";
import checker from "vite-plugin-checker";
import react from "@vitejs/plugin-react";

export default defineConfig({
plugins: [checker({ typescript: true }), react()],
});
Loading