|
| 1 | +<div align="center"> |
| 2 | + |
| 3 | +<a href="https://github.com/typescript-cheatsheets/react-typescript-cheatsheet/issues/81"> |
| 4 | + <img |
| 5 | + height="90" |
| 6 | + width="90" |
| 7 | + alt="react + ts logo" |
| 8 | + src="https://user-images.githubusercontent.com/6764957/53868378-2b51fc80-3fb3-11e9-9cee-0277efe8a927.png" |
| 9 | + align="left" |
| 10 | + /> |
| 11 | +</a> |
| 12 | + |
| 13 | +<p>Cheatsheets para desarrolladores expertos en React que comienzan con TypeScript</p> |
| 14 | + |
| 15 | +[**Básico**](https://github.com/typescript-cheatsheets/react-typescript-cheatsheet#basic-cheatsheet-table-of-contents) | |
| 16 | +[**Avanzado**](https://github.com/typescript-cheatsheets/react-typescript-cheatsheet-es/blob/master/AVANZADO.md) | |
| 17 | +[**Migrando**](https://github.com/typescript-cheatsheets/react-typescript-cheatsheet/blob/master/MIGRATING.md) | |
| 18 | +[**HOC**](https://github.com/typescript-cheatsheets/react-typescript-cheatsheet/blob/master/HOC.md) | |
| 19 | +[**Inglés**](https://github.com/typescript-cheatsheets/react-typescript-cheatsheet) | |
| 20 | +[**中文翻译**](https://github.com/fi3ework/blog/tree/master/react-typescript-cheatsheet-cn) | |
| 21 | +[Contribuir](https://github.com/typescript-cheatsheets/react-typescript-cheatsheet-es/blob/master/CONTRIBUYENDO.md) | |
| 22 | +[Preguntas](https://github.com/typescript-cheatsheets/react-typescript-cheatsheet-es/issues/new) |
| 23 | + |
| 24 | +</div> |
| 25 | + |
| 26 | +--- |
| 27 | + |
| 28 | +# Migrando (a TypeScript) Cheatsheet |
| 29 | + |
| 30 | +Este Cheatsheet recopila consejos y utilidades de casos de estudios reales de equipos que mueven bases de código significativas de JS plano o Flow a Typescript. Esto no intenta _convencer_ a la gente para que lo haga, pero recopilamos las pocas estadísticas que ofrecen las empresas después de su experiencia de migración. |
| 31 | + |
| 32 | +> ⚠️ Este Cheatsheet es extremadamente nuevo y podría usar toda la ayuda que podamos obtener. Consejos sólidos, resultados, y contenido actualizado son bienvenidos. |
| 33 | +
|
| 34 | +## Prerrequisitos |
| 35 | +Leer la [Guía oficial de TypeScript para migrar desde JS](https://www.typescriptlang.org/docs/handbook/migrating-from-javascript.html) y también deberías estar familiarizado con la [Guía de conversión de React](https://github.com/Microsoft/TypeScript-React-Conversion-Guide#typescript-react-conversion-guide). |
| 36 | + |
| 37 | +## Enfoques de conversión general |
| 38 | + |
| 39 | +- Nivel 0: No uses TypeScript, usa JSDoc |
| 40 | + - Mira nuestra [seccion de JSDoc](#JSDoc) |
| 41 | +- Nivel 1A: JavaScript mayoritario, TypeScript cada vez más estricto |
| 42 | + - como recomienda la [guía oficial de TS](https://www.typescriptlang.org/docs/handbook/migrating-from-javascript.html) |
| 43 | + - usa `allowJS` (Experiencias: [clayallsop][clayallsop], [pleo][pleo]) |
| 44 | +- Nivel 1B: Renombrar todo a TypeScript desde el principio |
| 45 | + - "[Just rename all .js files to .ts](https://twitter.com/jamonholmgren/status/1089241726303199232)"? |
| 46 | + - usa lo mas simple, la configuración mas mínima para comenzar |
| 47 | +- Nivel 2: TypeScript estricto |
| 48 | + - usa [`dts-gen`](https://github.com/Microsoft/dts-gen) de Microsoft para generar archivos `.d.ts` para tus archivos sin tipo. [Esta respuesta de SO](https://stackoverflow.com/questions/12687779/how-do-you-produce-a-d-ts-typings-definition-file-from-an-existing-javascript) tiene mas información sobre el tema. |
| 49 | + - usa la palabra clasve `declare` para declaraciones de ambiente - mira la [declaración de fusión](https://github.com/typescript-cheatsheets/react-typescript-cheatsheet#troubleshooting-handbook-bugs-in-official-typings) para parchear declaraciones de biblioteca en línea. |
| 50 | + |
| 51 | +Varios consejos/enfoques que las empresas exitosas han tomado |
| 52 | + |
| 53 | +- `@ts-ignore` en errores del compilador para librerias sin typedefs. |
| 54 | +- elije ESLint sobre TSLint (fuente: [ESLint](https://eslint.org/blog/2019/01/future-typescript-eslint) y [TS Roadmap](https://github.com/Microsoft/TypeScript/issues/29288)). [Puedes convertir TSlint a ESlint con esta herramienta](https://github.com/typescript-eslint/tslint-to-eslint-config). |
| 55 | +- El nuevo código siempre de escribirse en TypeScript. Sin excepciones. Para el código existente: Si tu tarea requiere cambiar el código JavaScript, debes volverlo a escribir. (Source: [Hootsuite][hootsuite]) |
| 56 | + |
| 57 | +<details> |
| 58 | +<summary> |
| 59 | +<b> |
| 60 | +Consejos para Webpack |
| 61 | +</b> |
| 62 | +</summary> |
| 63 | + |
| 64 | +- webpack loader: `awesome-typescript-loader` vs `ts-loader`? (Hay un cierto desacuerdo en la comunidad sobre esto - pero lee [awesome's point of view](https://github.com/s-panferov/awesome-typescript-loader#differences-between-ts-loader)) |
| 65 | +- configuración de Webpack: |
| 66 | + |
| 67 | +```js |
| 68 | +module.exports = { |
| 69 | + |
| 70 | +resolve: { |
| 71 | +- extensions: ['.js', '.jsx'] |
| 72 | ++ extensions: ['.ts', '.tsx', '.js', '.jsx'] |
| 73 | +}, |
| 74 | + |
| 75 | +// Soporte para source maps ('inline-source-map' también funciona) |
| 76 | +devtool: 'source-map', |
| 77 | + |
| 78 | +// Añadir el loader para archivos .ts. |
| 79 | +module: { |
| 80 | + loaders: [{ |
| 81 | +- test: /\.jsx?$/, |
| 82 | +- loader: 'babel-loader', |
| 83 | +- exclude: [/node_modules/], |
| 84 | ++ test: /\.(t|j)sx?$/, |
| 85 | ++ loader: ['awesome-typescript-loader?module=es6'], |
| 86 | ++ exclude: [/node_modules/] |
| 87 | ++ }, { |
| 88 | ++ test: /\.js$/, |
| 89 | ++ loader: 'source-map-loader', |
| 90 | ++ enforce: 'pre' |
| 91 | + }] |
| 92 | +} |
| 93 | +}; |
| 94 | +``` |
| 95 | + |
| 96 | +Nota especial sobre `ts-loader` y librerias de terceros: https://twitter.com/acemarke/status/1091150384184229888 |
| 97 | + |
| 98 | +</details> |
| 99 | + |
| 100 | +## JSDoc |
| 101 | + |
| 102 | +- https://github.com/Microsoft/TypeScript/wiki/JsDoc-support-in-JavaScript |
| 103 | +- El código base de webpack usa JSDoc con linting de TS https://twitter.com/TheLarkInn/status/984479953927327744 (un truco loco: https://twitter.com/thelarkinn/status/996475530944823296) |
| 104 | + |
| 105 | +Problemas a tener en cuenta: |
| 106 | + |
| 107 | +- `object` se convierte a `any` por alguna razón. |
| 108 | +- Si tiene un error en el JSDoc, no recibes ningún warning/error. TS just silently doesn't type annotate the function. |
| 109 | +- [El casteo puede ser detallado](https://twitter.com/bahmutov/status/1089229349637754880) |
| 110 | + |
| 111 | +(_gracias [Gil Tayar](https://twitter.com/giltayar/status/1089228919260221441) y [Gleb Bahmutov](https://twitter.com/bahmutov/status/1089229196247908353) por compartir el comentario anterior_) |
| 112 | + |
| 113 | +## Desde JS |
| 114 | + |
| 115 | +### Conversión automatizada de JS a TS |
| 116 | + |
| 117 | +- [TypeStat](https://github.com/JoshuaKGoldberg/TypeStat) ([usado por Codecademy](https://mobile.twitter.com/JoshuaKGoldberg/status/1159090281314160640)) |
| 118 | +- [TypeWiz](https://github.com/urish/typewiz) |
| 119 | +- [js-to-ts-converter](https://github.com/gregjacobs/js-to-ts-converter) |
| 120 | + |
| 121 | +### Conversión manual de JS a TS |
| 122 | + |
| 123 | +la estrategia de "Solo renombra" |
| 124 | + |
| 125 | +- OSX/Linux: `find src -name "*.js" -exec sh -c 'mv"$0" "${0%.js}.tsx"' {} \;` |
| 126 | + |
| 127 | +Puede cargar archivos de TypeScript con webpack o usar el compilador `tsc` para compilar sus archivos TS en JS uno al lado del otro. El `tsconfig.json` básico es: |
| 128 | + |
| 129 | +```json |
| 130 | +{ |
| 131 | + "compilerOptions": { |
| 132 | + "allowJs": true |
| 133 | + } |
| 134 | +} |
| 135 | +``` |
| 136 | + |
| 137 | +Luego querrás habilitarlo para validar JS: |
| 138 | + |
| 139 | +```json |
| 140 | +{ |
| 141 | + "compilerOptions": { |
| 142 | + "allowJs": true, |
| 143 | + "checkJs": true |
| 144 | + } |
| 145 | +} |
| 146 | +``` |
| 147 | + |
| 148 | +Si tiene una base de código grande y arroja demasiados errores a la vez, puedes optar por excluir archivos problemáticos con `//@ts-nocheck` o en su lugar desactivar `checkJs` y agregar una directiva `// @ ts-check` en la parte superior de cada archivo JS normal. |
| 149 | + |
| 150 | +TypeScript debería arrojar algunos errores atroces aquí que deberían ser fáciles de solucionar. |
| 151 | + |
| 152 | +Una vez que haya terminado, trague la píldora roja apagando los `any` implícitos: |
| 153 | + |
| 154 | +```js |
| 155 | +{ |
| 156 | + "compilerOptions": { |
| 157 | + "allowJs": true, |
| 158 | + "checkJs": true, |
| 159 | + "noImplicitAny": true // o "strict": true |
| 160 | + } |
| 161 | +} |
| 162 | +``` |
| 163 | + |
| 164 | +Esto generará un montón de errores de tipo y puedes comenzar a convertir archivos a TS u (opcionalmente) usar [anotaciones JSDoc](https://www.typescriptlang.org/docs/handbook/type-checking-javascript-files.html) en tu JS. |
| 165 | + |
| 166 | + |
| 167 | +Una práctica común es usar alias de tipo TODO para `any`, para que puedas hacer un seguimiento de lo que necesita hacer luego. |
| 168 | + |
| 169 | +```ts |
| 170 | +type TODO_TYPEME = any; |
| 171 | +export function myFunc(foo: TODO_TYPEME, bar: TODO_TYPEME): number { |
| 172 | + // ... |
| 173 | +} |
| 174 | +``` |
| 175 | + |
| 176 | +Gradualmente agrega [mas banderas de modo `strict`](https://www.typescriptlang.org/docs/handbook/compiler-options.html) como `noImplicitThis`, `strictNullChecks`, y así sucesivamente hasta que finalmente pueda correr por completo en modo estricto sin que queden archivos js: |
| 177 | + |
| 178 | +```js |
| 179 | +{ |
| 180 | + "compilerOptions": { |
| 181 | + "strict": true |
| 182 | + } |
| 183 | +} |
| 184 | +``` |
| 185 | + |
| 186 | +**Más recursos** |
| 187 | + |
| 188 | +- [Adopting TypeScript at Scale - AirBnB's conversion story and strategy](https://www.youtube.com/watch?v=P-J9Eg7hJwE) |
| 189 | +- [Migrating a `create-react-app`/`react-scripts` app to TypeScript](https://facebook.github.io/create-react-app/docs/adding-typescript) - don't use `react-scripts-ts` |
| 190 | +- [Migrating an EJECTED CRA app to TS](https://spin.atomicobject.com/2018/07/04/migrating-cra-typescript/) |
| 191 | +- [Lyft's JS to TS migration tool](https://github.com/lyft/react-javascript-to-typescript-transform) (includes PropTypes migration) |
| 192 | +- [Hootsuite][hootsuite] |
| 193 | +- [Storybook's migration (PR)](https://github.com/storybooks/storybook/issues/5030) |
| 194 | +- [How we migrated a 200K+ LOC project to TypeScript and survived to tell the story][coherentlabs] - Coherent Labs - using `grunt-ts`, jQuery and Kendo UI |
| 195 | + |
| 196 | +Contenido antiguo que posiblemente esté desactualizado |
| 197 | + |
| 198 | +- [Incrementally Migrating JS to TS][clayallsop] (old) |
| 199 | +- [Microsoft's TypeScript React Conversion Guide][mstsreactconversionguide] (old) |
| 200 | + |
| 201 | +## Desde Flow |
| 202 | + |
| 203 | +- Try flow2ts: `npx flow2ts` - doesn't work 100% but saves some time ([mira este y otros tips de @braposo](https://github.com/typescript-cheatsheets/react-typescript-cheatsheet/pull/79#issuecomment-458227322) at TravelRepublic) |
| 204 | +- [Incremental Migration to TypeScript on a Flowtype codebase][entria] at Entria |
| 205 | +- [MemSQL's Studio's migration](https://davidgom.es/porting-30k-lines-of-code-from-flow-to-typescript/) - blogpost con muchos tips útiles |
| 206 | +- Retail-UI's Codemod: https://github.com/skbkontur/retail-ui/tree/master/packages/react-ui-codemodes/flow-to-ts |
| 207 | +- Quick-n-dirty [Flow to TS Codemod](https://gist.github.com/skovhus/c57367ce6ecbc3f70bb7c80f25727a11) |
| 208 | +- [Ecobee's brief experience](https://mobile.twitter.com/alanhietala/status/1104450494754377728) |
| 209 | +- [Migrating a 50K SLOC Flow + React Native app to TypeScript](https://blog.usejournal.com/migrating-a-flow-react-native-app-to-typescript-c74c7bceae7d) |
| 210 | + |
| 211 | +## Resultados |
| 212 | + |
| 213 | +- El número de despliegues de producción se duplicó para [Hootsuite][hootsuite] |
| 214 | +- Se encontraron globals accidentales para [Tiny][tiny] |
| 215 | +- Se encontraron llamadas a funciones incorrectas para [Tiny][tiny] |
| 216 | +- Se encontró un código de error poco utilizado que no se probó [Tiny][tiny] |
| 217 | + |
| 218 | +## Estudios Académicos de Migración |
| 219 | + |
| 220 | +- [To Type or Not to Type: Quantifying Detectable Bugs in JavaScript](http://earlbarr.com/publications/typestudy.pdf) |
| 221 | + |
| 222 | +> Nuestro hallazgo central es que ambos sistemas de tipos estáticos encuentran un porcentaje importante de errores públicos: tanto Flow 0.30 como TypeScript 2.0 detectan con éxito el 15%. |
| 223 | +
|
| 224 | +## Diversas historias de migración de compañías notables y fuentes abiertas |
| 225 | + |
| 226 | + |
| 227 | +- [Adopting TypeScript at Scale - AirBnB's conversion story and strategy](https://www.youtube.com/watch?v=P-J9Eg7hJwE) |
| 228 | +- [Lyft](https://eng.lyft.com/typescript-at-lyft-64f0702346ea) |
| 229 | +- [Google](http://neugierig.org/software/blog/2018/09/typescript-at-google.html) |
| 230 | +- [Tiny][tiny] - [Talk from ForwardJS here](https://www.slideshare.net/tiny/porting-100k-lines-of-code-to-typescript) |
| 231 | +- [Slack](https://slack.engineering/typescript-at-slack-a81307fa288d) ([podcast](https://softwareengineeringdaily.com/2017/08/11/typescript-at-slack-with-felix-rieseberg/)) |
| 232 | +- [Priceline](https://medium.com/priceline-labs/trying-out-typescript-part-1-15a5267215b9) |
| 233 | +- Dropbox - [Talk at React Loop](https://www.youtube.com/watch?v=veXkJq0Z2Qk) |
| 234 | + |
| 235 | +Código abierto |
| 236 | + |
| 237 | +- [Jest's migration (PR)](https://github.com/facebook/jest/pull/7554#issuecomment-454358729) |
| 238 | +- [Expo's migration (issue)](https://github.com/expo/expo/issues/2164) |
| 239 | +- [Google Workbox migration](https://github.com/GoogleChrome/workbox/pull/2058) |
| 240 | +- [Atlassian's migration (PR)](https://github.com/atlassian/react-beautiful-dnd/issues/982) |
| 241 | +- [Yarn's migration (issue)](https://github.com/yarnpkg/yarn/issues/6953) |
| 242 | +- [React Native CLI](https://github.com/react-native-community/cli/issues/683) |
| 243 | +- [Next.js](https://nextjs.org/blog/next-9) |
| 244 | +- [Redux](https://github.com/reduxjs/redux/pull/3536) |
| 245 | + |
| 246 | +## Enlaces |
| 247 | + |
| 248 | +[hootsuite]: https://medium.com/hootsuite-engineering/thoughts-on-migrating-to-typescript-5e1a04288202 "Thoughts on migrating to TypeScript" |
| 249 | +[clayallsop]: https://medium.com/@clayallsopp/incrementally-migrating-javascript-to-typescript-565020e49c88 "Incrementally Migrating JavaScript to TypeScript" |
| 250 | +[pleo]: https://medium.com/pleo/migrating-a-babel-project-to-typescript-af6cd0b451f4 "Migrating a Babel project to TypeScript" |
| 251 | +[mstsreactconversionguide]: https://github.com/Microsoft/TypeScript-React-Conversion-Guide "TypeScript React Conversion Guide" |
| 252 | +[entria]: https://medium.com/entria/incremental-migration-to-typescript-on-a-flowtype-codebase-515f6490d92d "Incremental Migration to TypeScript on a Flowtype codebase" |
| 253 | +[coherentlabs]: https://hashnode.com/post/how-we-migrated-a-200k-loc-project-to-typescript-and-survived-to-tell-the-story-ciyzhikcc0001y253w00n11yb "How we migrated a 200K+ LOC project to TypeScript and survived to tell the story" |
| 254 | +[tiny]: https://go.tiny.cloud/blog/benefits-of-gradual-strong-typing-in-javascript/ "Benefits of gradual strong typing in JavaScript" |
0 commit comments