Reemplazando Scripts de Shell con TypeScript Multiplataforma

Rate this content
Bookmark

Los scripts de shell cumplen un propósito útil, pero tienen algunas desventajas. ¿Qué pasaría si pudiéramos superar estos problemas y hacer que nuestros scripts sean más poderosos utilizando TypeScript multiplataforma familiar? En esta charla, discutiremos por qué deberías cambiar tus scripts de shell a TypeScript y demostraremos un enfoque posible.

David Sherret
David Sherret
8 min
21 Sep, 2023

Video Summary and Transcription

El orador discute los beneficios de reemplazar los scripts de shell con TypeScript, destacando las limitaciones de los scripts de shell y las ventajas de TypeScript, como la compatibilidad multiplataforma y una mejor herramienta. Deno se presenta como la plataforma ideal para scripts de un solo archivo, con soporte incorporado para TypeScript, instalación automática de dependencias y sandboxing. Se menciona la biblioteca dax como una herramienta útil para scripts, que proporciona una shell multiplataforma y otras API. En general, la charla enfatiza el poder y la flexibilidad de usar TypeScript y Deno para fines de scripting.

Available in English

1. Why Replace Shell Scripts with TypeScript

Short description:

Soy David Sherrit, un desarrollador en Deno, y hoy hablaré sobre por qué deberías reemplazar tus scripts de shell con TypeScript multiplataforma. TypeScript no es mi lenguaje principal, pero lo uso en casi todos mis proyectos, y esta charla explicará cómo y por qué también deberías considerar hacerlo. A menudo usamos scripts de shell porque funcionan de inmediato en el sistema en el que estamos, pero tienen desventajas. Los scripts de shell dependen del sistema, no se pueden ejecutar en todas las plataformas y no funcionan en Windows de inmediato. TypeScript, por otro lado, es familiar, tiene excelentes herramientas y permite la creación de scripts multiplataforma en Deno.

Hola a todos. Soy David Sherrit, un desarrollador en Deno, y hoy hablaré sobre por qué deberías reemplazar tus scripts de shell con TypeScript multiplataforma. Esto no es solo una charla para desarrolladores de JavaScript, sino para desarrolladores de cualquier lenguaje y experiencia.

Personalmente, TypeScript no es mi lenguaje principal, pero lo uso en casi todos mis proyectos, y esta charla explicará cómo y por qué también deberías considerar hacerlo.

Entonces, ¿por qué usamos scripts de shell? A menudo los usamos porque funcionan de inmediato en el sistema en el que estamos, por lo que es conveniente. Son fáciles de ejecutar. Tienen una sintaxis concisa y se ejecutan de manera similar a lo que escribimos en la línea de comandos. Entonces, si tienes un comando que ejecutas con frecuencia en tu terminal, a menudo puedes copiarlo y pegarlo en tu script de shell. Sin embargo, hay algunas desventajas. La primera gran desventaja es que dependen del sistema. Los scripts de shell no se pueden ejecutar en todas las plataformas. En su mayoría, no se ejecutarán de inmediato en Windows. A veces, esto también ocurre en sistemas basados en Unix, dependiendo de cómo esté escrito el script de shell. Además, los comandos básicos de Unix no funcionan de inmediato en Windows. Y decirles a los desarrolladores de Windows que usen WSL no es una gran solución. Eso puede requerir que configuren un nuevo entorno de desarrollo dentro de WSL solo para ejecutar el script. Los scripts de shell son excelentes si estás ejecutando unos pocos comandos, pero es difícil aumentar la funcionalidad sin aumentar drásticamente la complejidad.

Otro punto específico para los desarrolladores de JavaScript es que los scripts de shell presentan código que debemos mantener en otro lenguaje. Tampoco podemos usar nuestras bibliotecas favoritas de JavaScript. Por último, no hay verificación de tipos. No obtenemos autocompletado de código para ayudarnos a desarrollar y todas las demás herramientas agradables que TypeScript proporciona.

Ahora, ¿por qué deberías usar TypeScript en lugar de scripts de shell? En primer lugar, es familiar, y TypeScript y JavaScript son lenguajes populares con una gran comunidad. Muchos desarrolladores al menos han tocado JavaScript o al menos pueden entender su sintaxis. En segundo lugar, está la verificación de tipos y las herramientas. Un gran beneficio de TypeScript es que sus herramientas son excelentes, incluso si solo estamos usando JavaScript. Obtenemos funciones como autocompletado de código, ir a la definición y errores de verificación de tipos en el editor.

Esta charla no solo trata sobre por qué deberías reemplazar los scripts de shell con TypeScript, sino también por qué deberías usar Deno mientras lo haces. En primer lugar, es mucho más fácil escribir scripts multiplataforma en Deno que scripts de shell, porque la mayoría de las API funcionan en varias plataformas. Obviamente, hay algunas API específicas de la plataforma, si las necesitas, pero generalmente no tenemos que recurrir a ellas.

2. Advantages of Deno for Single File Scripting

Short description:

Deno es la mejor plataforma para escribir scripts de un solo archivo. Admite TypeScript de forma nativa, instala automáticamente las dependencias según el código y está sandboxed por defecto. Deno también te permite definir las dependencias en el propio archivo de script, lo que facilita alojar los scripts en un servidor web. Además, la biblioteca dax proporciona una shell multiplataforma con comandos comunes de Unix y otras API útiles para scripting. Si bien lanzar comandos puede ser un poco más verboso que los scripts de shell, las ventajas de escribir scripts en JavaScript superan esto. En general, Deno ofrece un entorno potente y flexible para scripting de un solo archivo.

En segundo lugar, tenemos los scripts de un solo archivo. Obviamente, estoy sesgado, pero creo que Deno es la mejor plataforma para escribir scripts de un solo archivo. Por ejemplo, en Node, usar TypeScript requiere una configuración adicional. Necesitas tener un archivo package.json para definir las dependencias. Esto también requiere que cualquier persona que ejecute tus scripts recuerde ejecutar npm install primero y también después de cualquier cambio en las dependencias. Ese proceso crea una carpeta de módulos de Node en el árbol de directorios. Por lo tanto, ya tienes dos entradas adicionales en el sistema de archivos, por lo que no es un script de un solo archivo.

Por otro lado, en Deno, TypeScript es compatible de forma nativa, por lo que puedes ejecutar código TypeScript directamente. Es opcional usar un archivo de configuración para definir tus dependencias, y también es opcional tener una carpeta de módulos de Node para las dependencias de npm. Es importante tener en cuenta que aún puedes usar ese modelo si lo deseas, pero es opcional. En tercer lugar, las dependencias se instalan automáticamente según el código, por lo que no es necesario ejecutar un comando de configuración separado como npm install.

Finalmente, Deno está sandboxed por defecto. Node recientemente obtuvo un sistema de permisos experimental, pero es opcional en lugar de ser obligatorio. Otra gran ventaja de Deno para scripting de un solo archivo es que es posible definir las dependencias en el propio archivo de script. Por ejemplo, puedes importar paquetes de npm o usar importaciones https para alojar fácilmente scripts en un servidor web y hacer referencia a ellos directamente. Una parte negativa de esto es que es verboso lanzar subprocesos utilizando una API de proceso de bajo nivel disponible tanto en Node como en Deno. Pero eso no es un gran problema, porque podemos importar una dependencia que ayuda a que sea más similar a los scripts de shell. Hay una biblioteca que escribí llamada dax. Dax es una shell multiplataforma escrita en JavaScript que tiene comandos comunes de Unix integrados. También tiene otras API útiles para ayudar con el scripting.

Aquí hay algunos ejemplos de ejecución de comandos. La sintaxis de la shell que admite es una sintaxis común que se encuentra en los scripts de shell. Para casos más complejos, como bucles, probablemente quieras usar JavaScript en su lugar. Nuevamente, para enfatizar, todo el código mostrado aquí funciona en Windows. Lanzar comandos es un poco más verboso que los scripts de shell para casos simples, pero en mi opinión, las ventajas de poder escribir estos scripts principalmente en JavaScript superan la ligera verbosidad adicional al lanzar comandos. Además, se podría argumentar que esto es menos verboso en casos complejos. Por ejemplo, como se muestra en la última línea de este código, acceder a las propiedades de la salida JSON de un comando es bastante fácil.

Finalmente, DAX tiene API de registro, una API de ruta. Por ejemplo, aquí creamos un objeto de referencia de ruta para el directorio fuente, verificamos si es un directorio y luego llamamos a mkdir para crear el directorio. Luego obtenemos una referencia a un archivo de texto dentro de ese directorio, escribimos algo de texto en él o incluso podríamos leer desde ese archivo de texto. O podríamos escribir algún objeto como JSON en un archivo o leerlo deserializándolo en un valor JSON. También hay API para hacer preguntas, hacer selecciones y mostrar progreso. Finalmente, hay una API de solicitud incorporada que es similar a la API fetch, pero menos propensa a errores y con algunas funciones adicionales.

De todos modos, hay mucho más en esto, y recomendaría consultar la documentación para obtener más detalles. Gracias por escuchar mi charla.

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

TypeScript and React: Secrets of a Happy Marriage
React Advanced Conference 2022React Advanced Conference 2022
21 min
TypeScript and React: Secrets of a Happy Marriage
Top Content
TypeScript and React are inseparable. What's the secret to their successful union? Quite a lot of surprisingly strange code. Learn why useRef always feels weird, how to wrangle generics in custom hooks, and how union types can transform your components.
React's Most Useful Types
React Day Berlin 2023React Day Berlin 2023
21 min
React's Most Useful Types
Top Content
We don't think of React as shipping its own types. But React's types are a core part of the framework - overseen by the React team, and co-ordinated with React's major releases.In this live coding talk, we'll look at all the types you've been missing out on. How do you get the props type from a component? How do you know what ref a component takes? Should you use React.FC? And what's the deal with JSX.Element?You'll walk away with a bunch of exciting ideas to take to your React applications, and hopefully a new appreciation for the wonders of React and TypeScript working together.
Stop Writing Your Routes
Vue.js London 2023Vue.js London 2023
30 min
Stop Writing Your Routes
The more you keep working on an application, the more complicated its routing becomes, and the easier it is to make a mistake. ""Was the route named users or was it user?"", ""Did it have an id param or was it userId?"". If only TypeScript could tell you what are the possible names and params. If only you didn't have to write a single route anymore and let a plugin do it for you. In this talk we will go through what it took to bring automatically typed routes for Vue Router.
Making Magic: Building a TypeScript-First Framework
TypeScript Congress 2023TypeScript Congress 2023
31 min
Making Magic: Building a TypeScript-First Framework
I'll dive into the internals of Nuxt to describe how we've built a TypeScript-first framework that is deeply integrated with the user's IDE and type checking setup to offer end-to-end full-stack type safety, hints for layouts, middleware and more, typed runtime configuration options and even typed routing. Plus, I'll highlight what I'm most excited about doing in the days to come and how TypeScript makes that possible not just for us but for any library author.
Full-stack & typesafe React (+Native) apps with tRPC.io
React Advanced Conference 2021React Advanced Conference 2021
6 min
Full-stack & typesafe React (+Native) apps with tRPC.io
Top Content
Why are we devs so obsessed with decoupling things that are coupled nature? tRPC is a library that replaces the need for GraphQL or REST for internal APIs. When using it, you simply write backend functions whose input and output shapes are instantly inferred in your frontend without any code generation; making writing API schemas a thing of the past. It's lightweight, not tied to React, HTTP-cacheable, and can be incrementally adopted. In this talk, I'll give a glimpse of the DX you can get from tRPC and how (and why) to get started.
Faster TypeScript builds with --isolatedDeclarations
TypeScript Congress 2023TypeScript Congress 2023
24 min
Faster TypeScript builds with --isolatedDeclarations
Top Content
Type-checking a TypeScript codebase can be slow, especially for monorepos containing lots of projects that each need to use the type checker to generate type declaration files. In this talk, we introduce — for the very first time — a new TypeScript feature we are working on called “Isolated Declarations” that allows DTS files to be generated without using the type checker at all! This opens the door to faster declaration generation in TypeScript itself, as well as in external tools written in other languages such as ESBuild and swc. You'll see how to use this new option, and maybe (just maybe) you’ll be convinced about the benefits of explicit return types! Most importantly, we will show how Isolated Declarations enables parallel builds to spread work across your CPU cores to significantly improve the build speed of your TypeScript projects.

Workshops on related topic

React, TypeScript, and TDD
React Advanced Conference 2021React Advanced Conference 2021
174 min
React, TypeScript, and TDD
Top Content
Featured WorkshopFree
Paul Everitt
Paul Everitt
ReactJS is wildly popular and thus wildly supported. TypeScript is increasingly popular, and thus increasingly supported.

The two together? Not as much. Given that they both change quickly, it's hard to find accurate learning materials.

React+TypeScript, with JetBrains IDEs? That three-part combination is the topic of this series. We'll show a little about a lot. Meaning, the key steps to getting productive, in the IDE, for React projects using TypeScript. Along the way we'll show test-driven development and emphasize tips-and-tricks in the IDE.
Best Practices and Advanced TypeScript Tips for React Developers
React Advanced Conference 2022React Advanced Conference 2022
148 min
Best Practices and Advanced TypeScript Tips for React Developers
Top Content
Featured Workshop
Maurice de Beijer
Maurice de Beijer
Are you a React developer trying to get the most benefits from TypeScript? Then this is the workshop for you.In this interactive workshop, we will start at the basics and examine the pros and cons of different ways you can declare React components using TypeScript. After that we will move to more advanced concepts where we will go beyond the strict setting of TypeScript. You will learn when to use types like any, unknown and never. We will explore the use of type predicates, guards and exhaustive checking. You will learn about the built-in mapped types as well as how to create your own new type map utilities. And we will start programming in the TypeScript type system using conditional types and type inferring.
Deep TypeScript Tips & Tricks
Node Congress 2024Node Congress 2024
83 min
Deep TypeScript Tips & Tricks
Top Content
Workshop
Josh Goldberg
Josh Goldberg
TypeScript has a powerful type system with all sorts of fancy features for representing wild and wacky JavaScript states. But the syntax to do so isn't always straightforward, and the error messages aren't always precise in telling you what's wrong. Let's dive into how many of TypeScript's more powerful features really work, what kinds of real-world problems they solve, and how to wrestle the type system into submission so you can write truly excellent TypeScript code.
Practice TypeScript Techniques Building React Server Components App
TypeScript Congress 2023TypeScript Congress 2023
131 min
Practice TypeScript Techniques Building React Server Components App
Workshop
Maurice de Beijer
Maurice de Beijer
In this hands-on workshop, Maurice will personally guide you through a series of exercises designed to empower you with a deep understanding of React Server Components and the power of TypeScript. Discover how to optimize your applications, improve performance, and unlock new possibilities.
 
During the workshop, you will:
- Maximize code maintainability and scalability with advanced TypeScript practices
- Unleash the performance benefits of React Server Components, surpassing traditional approaches
- Turbocharge your TypeScript with the power of Mapped Types
- Make your TypeScript types more secure with Opaque Types
- Explore the power of Template Literal Types when using Mapped Types
 
Maurice will virtually be by your side, offering comprehensive guidance and answering your questions as you navigate each exercise. By the end of the workshop, you'll have mastered React Server Components, armed with a newfound arsenal of TypeScript knowledge to supercharge your React applications.
 
Don't miss this opportunity to elevate your React expertise to new heights. Join our workshop and unlock the potential of React Server Components with TypeScript. Your apps will thank you.
Advanced TypeScript types for fun and reliability
TypeScript Congress 2022TypeScript Congress 2022
116 min
Advanced TypeScript types for fun and reliability
Workshop
Maurice de Beijer
Maurice de Beijer
If you're looking to get the most out of TypeScript, this workshop is for you! In this interactive workshop, we will explore the use of advanced types to improve the safety and predictability of your TypeScript code. You will learn when to use types like unknown or never. We will explore the use of type predicates, guards and exhaustive checking to make your TypeScript code more reliable both at compile and run-time. You will learn about the built-in mapped types as well as how to create your own new type map utilities. And we will start programming in the TypeScript type system using conditional types and type inferring.
Are you familiar with the basics of TypeScript and want to dive deeper? Then please join me with your laptop in this advanced and interactive workshop to learn all these topics and more.
You can find the slides, with links, here: http://theproblemsolver.nl/docs/ts-advanced-workshop.pdf
And the repository we will be using is here: https://github.com/mauricedb/ts-advanced
Mastering Node.js Test Runner
TestJS Summit 2023TestJS Summit 2023
78 min
Mastering Node.js Test Runner
Workshop
Marco Ippolito
Marco Ippolito
Node.js test runner is modern, fast, and doesn't require additional libraries, but understanding and using it well can be tricky. You will learn how to use Node.js test runner to its full potential. We'll show you how it compares to other tools, how to set it up, and how to run your tests effectively. During the workshop, we'll do exercises to help you get comfortable with filtering, using native assertions, running tests in parallel, using CLI, and more. We'll also talk about working with TypeScript, making custom reports, and code coverage.