¿Están equivocados los tipos de módulo?

Rate this content
Bookmark
GithubProject website

¿Alguna vez has instalado una dependencia, la has importado tal como indica el README y te has encontrado inmediatamente con extraños errores de TypeScript sobre importaciones por defecto, el formato de módulo de salida o la interoperabilidad ESM/CommonJS? Cuando todo funciona en tiempo de ejecución pero TypeScript se queja, es posible que te preguntes, ¿es esto un error de TypeScript? O... ¿los tipos están equivocados?


El panorama de los módulos y la publicación de paquetes en JavaScript es complicado. Casi un tercio de los paquetes npm más populares que incluyen tipos tienen algún tipo de problema relacionado con los tipos de módulo que puede causar confusión a los usuarios. Pero las cosas están empezando a mejorar. En esta charla, vamos a:

- explorar cómo llegamos hasta aquí, ¿por qué las cosas son complicadas?
- desarrollar un modelo mental simple y preciso de cómo TypeScript ve los paquetes
- ver cómo la herramienta `arethetypeswrong` puede ayudar a detectar problemas antes de la publicación
- analizar las tendencias en los datos de `arethetypeswrong` para paquetes populares a lo largo del tiempo
- discutir los próximos pasos para mejorar el ecosistema de paquetes con tipos

Andrew Branch
Andrew Branch
30 min
21 Sep, 2023

Comments

Sign in or register to post your comment.

Video Summary and Transcription

Esta charla analiza las complejidades y terminología del sistema de módulos, las discrepancias entre TypeScript y Node, y cómo solucionar los errores de TypeScript con el paquete Helmet. También explora la resolución de módulos y las discrepancias de tipos, los desafíos con el soporte de TypeScript y Node, y la necesidad de mejoras en paquetes populares.

Available in English

1. Introducción a los módulos y terminología

Short description:

Hola a todos. Mi nombre es Andrew y he estado en el equipo de TypeScript durante los últimos cuatro años. Hoy hablaremos sobre las complejidades del sistema de módulos y la terminología asociada, como ESM y CommonJS. Es importante estar familiarizado con las opciones de resolución de módulos y las diferencias entre Node.16 y Node.Next.

Muy bien. Hola a todos. Y gracias por unirse a mí para hablar sobre módulos. Mi nombre es Andrew. He estado en el equipo de TypeScript durante los últimos cuatro años, y tenemos mucho de qué hablar hoy en poco tiempo, así que eso es suficiente sobre mí. Y creo que todos sabemos que las complejidades del sistema de módulos son súper interesantes y divertidas, así que no hay tiempo para convencerte, pero si viste la charla de Mark Erickson y no tuviste suficiente, esta es definitivamente la charla para ti. Antes de comenzar, hay un poco de terminología que debemos cubrir. Voy a usar el término ESM o el acrónimo ESM alrededor de cien veces en esta charla. Eso significa Módulo ECMAScript. ESM es el sistema de módulos que se agregó a la especificación del lenguaje JavaScript en 2015. Y puedes reconocerlo por las palabras clave import y export. El otro sistema de módulos que discutiremos es CommonJS o CJS. Ese es el estándar de la comunidad que fue popularizado por Node antes de que existiera ESM. Si alguna vez has visto require y module.exports, eso es CommonJS y aún es compatible con Node. También tendré que mencionar algunas extensiones de archivo durante esta charla. Y como pueden superponerse con otros acrónimos, intentaré recordar pronunciarlos con un punto al principio. Será algo útil si estás al menos vagamente familiarizado con algunas opciones de resolución de módulos y TypeScript. Node.16 y Node.Next son actualmente idénticos, así que puedo llamarlos por cualquiera de los dos nombres. Son la única buena opción para Node moderno y no solo significa emitir módulos ES. Esa es una idea equivocada común. Históricamente, el que se llamaba Node era el que todos usaban para casi todo, pero realmente

2. Entendiendo el error de TypeScript con Helmet

Short description:

Vamos a analizar un confuso error de TypeScript con la dependencia de NPM Helmet. Cuando se compila a CommonJS, todo funciona bien. Sin embargo, al cambiar a módulos ES, se produce un error en el que helmet ya no se puede llamar. Vamos a investigar más a fondo ejecutando el código.

Helmet no se ha mantenido al día con las características modernas. Vamos a echar un vistazo a un error de TypeScript un tanto confuso aquí. Estoy mirando la dependencia de NPM llamada Helmet. Acabo de copiar y pegar el ejemplo del archivo README aquí. Esto se compila con TSC y se ejecuta en Node sin problemas. Puedes ver que actualmente estoy compilando a CommonJS. Si quiero cambiar a módulos ES aquí, puedo hacerlo agregando el campo type module a mi propio package JSON para el proyecto. Pero cuando hago eso y vuelvo aquí, ahora obtengo este confuso error de TypeScript que dice que helmet ya no se puede llamar. Si juego lo suficiente con esto, veré TypeScript

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

Vite: Rethinking Frontend Tooling
JSNation Live 2021JSNation Live 2021
31 min
Vite: Rethinking Frontend Tooling
Top Content
Vite is a new build tool that intends to provide a leaner, faster, and more friction-less workflow for building modern web apps. This talk will dive into the project's background, rationale, technical details and design decisions: what problem does it solve, what makes it fast, and how does it fit into the JS tooling landscape.
Scaling Up with Remix and Micro Frontends
Remix Conf Europe 2022Remix Conf Europe 2022
23 min
Scaling Up with Remix and Micro Frontends
Top Content
Do you have a large product built by many teams? Are you struggling to release often? Did your frontend turn into a massive unmaintainable monolith? If, like me, you’ve answered yes to any of those questions, this talk is for you! I’ll show you exactly how you can build a micro frontend architecture with Remix to solve those challenges.
React Compiler - Understanding Idiomatic React (React Forget)
React Advanced Conference 2023React Advanced Conference 2023
33 min
React Compiler - Understanding Idiomatic React (React Forget)
Top Content
React provides a contract to developers- uphold certain rules, and React can efficiently and correctly update the UI. In this talk we'll explore these rules in depth, understanding the reasoning behind them and how they unlock new directions such as automatic memoization. 
Full Stack Components
Remix Conf Europe 2022Remix Conf Europe 2022
37 min
Full Stack Components
Top Content
Remix is a web framework that gives you the simple mental model of a Multi-Page App (MPA) but the power and capabilities of a Single-Page App (SPA). One of the big challenges of SPAs is network management resulting in a great deal of indirection and buggy code. This is especially noticeable in application state which Remix completely eliminates, but it's also an issue in individual components that communicate with a single-purpose backend endpoint (like a combobox search for example).
In this talk, Kent will demonstrate how Remix enables you to build complex UI components that are connected to a backend in the simplest and most powerful way you've ever seen. Leaving you time to chill with your family or whatever else you do for fun.
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.
Making JavaScript on WebAssembly Fast
JSNation Live 2021JSNation Live 2021
29 min
Making JavaScript on WebAssembly Fast
Top Content
JavaScript in the browser runs many times faster than it did two decades ago. And that happened because the browser vendors spent that time working on intensive performance optimizations in their JavaScript engines.Because of this optimization work, JavaScript is now running in many places besides the browser. But there are still some environments where the JS engines can’t apply those optimizations in the right way to make things fast.We’re working to solve this, beginning a whole new wave of JavaScript optimization work. We’re improving JavaScript performance for entirely different environments, where different rules apply. And this is possible because of WebAssembly. In this talk, I'll explain how this all works and what's coming next.

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.
Using CodeMirror to Build a JavaScript Editor with Linting and AutoComplete
React Day Berlin 2022React Day Berlin 2022
86 min
Using CodeMirror to Build a JavaScript Editor with Linting and AutoComplete
Top Content
WorkshopFree
Hussien Khayoon
Kahvi Patel
2 authors
Using a library might seem easy at first glance, but how do you choose the right library? How do you upgrade an existing one? And how do you wade through the documentation to find what you want?
In this workshop, we’ll discuss all these finer points while going through a general example of building a code editor using CodeMirror in React. All while sharing some of the nuances our team learned about using this library and some problems we encountered.
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.
Testing Web Applications Using Cypress
TestJS Summit - January, 2021TestJS Summit - January, 2021
173 min
Testing Web Applications Using Cypress
WorkshopFree
Gleb Bahmutov
Gleb Bahmutov
This workshop will teach you the basics of writing useful end-to-end tests using Cypress Test Runner.
We will cover writing tests, covering every application feature, structuring tests, intercepting network requests, and setting up the backend data.
Anyone who knows JavaScript programming language and has NPM installed would be able to follow along.
Build a powerful DataGrid in few hours with Ag Grid
React Summit US 2023React Summit US 2023
96 min
Build a powerful DataGrid in few hours with Ag Grid
WorkshopFree
Mike Ryan
Mike Ryan
Does your React app need to efficiently display lots (and lots) of data in a grid? Do your users want to be able to search, sort, filter, and edit data? AG Grid is the best JavaScript grid in the world and is packed with features, highly performant, and extensible. In this workshop, you’ll learn how to get started with AG Grid, how we can enable sorting and filtering of data in the grid, cell rendering, and more. You will walk away from this free 3-hour workshop equipped with the knowledge for implementing AG Grid into your React application.
We all know that rolling our own grid solution is not easy, and let's be honest, is not something that we should be working on. We are focused on building a product and driving forward innovation. In this workshop, you'll see just how easy it is to get started with AG Grid.
Prerequisites: Basic React and JavaScript
Workshop level: Beginner