Migrating TypeScript to Modules: The Fine Details

Rate this content
Bookmark
SlidesGithub

In TypeScript 5.0, the TypeScript toolchain migrated to modules. In this talk, we'll get deep in the weeds, discussing what "modules" even are (and how we somehow weren't using them), the specifics of the migration itself, how we managed to make the switch "mid-flight" on an actively-developed project, how the migration went, and what's next.

FAQ

TypeScript's migration to modules involved changing the internal structure of the TypeScript compiler to utilize the import and export syntax instead of global namespaces. This major change involved transforming over a quarter million lines of code to improve modularity and maintainability.

The migration was challenging due to the massive size of the TypeScript codebase, frequent changes during the migration process, and the need to maintain compatibility and functionality throughout the transformation.

The migration utilized TS Morph for code transformation and Git for managing manual changes. TS Morph provided an effective way to handle TypeScript-to-TypeScript transformations while preserving formatting, and Git helped manage and apply changes in a controlled manner.

The migration to modules in TypeScript resulted in faster build times, reduced package sizes, and allowed the TypeScript team to use modern development tools and practices. It also enabled better handling of imports and exports which streamlined the development process.

To manage large files and frequent updates, the TypeScript team automated the migration process as much as possible, used code transformation tools, and implemented the changes in steps to facilitate easier review and debugging.

Post-migration plans included the removal of the prepend feature, exploration of shipping ECMAScript Modules (ESM), and potentially offering a clean ESM API. The team also aimed to improve code organization and minimize code cycles.

Jake Bailey
Jake Bailey
26 min
21 Sep, 2023

Comments

Sign in or register to post your comment.

Video Summary and Transcription

This Talk discusses TypeScript's migration to modules, the challenges faced, and the automation used for the migration. The TS Morph library and git are used for code transformation and managing changes. The final step involves converting TS dotted names to named imports. The migration to ESBuild brings benefits like faster development loop and improved import organization in TypeScript.

1. TypeScript's Migration to Modules

Short description:

Hey everyone, I'm Jake. Today, I'm going to talk about TypeScript's migration to modules. It was a huge change, completely changing the way the TypeScript compiler was structured internally. We'll discuss what a migration to modules means, why it was challenging, how I made it less painful, and what's next for modules in TypeScript. Modules in TypeScript refer to the import and export syntax, unlike the previous use of scripts. Namespaces, originally called internal modules, provided encapsulation, export, and import like modules, but with some differences.

Hey everyone, I'm Jake. I'm a senior software engineer at Microsoft, and today I'm going to talk about TypeScript's migration to modules.

So, first off, what are we even talking about? Well, in November of last year, I sent this PR. It was the culmination of many, many months of work. It was a huge change, some quarter of a million lines of code, and it completely changed the way the TypeScript compiler was structured internally. We talked about this in length on our blog, but there are plenty of details that we didn't get to talk about, and that's what I'm going to talk about today.

Real briefly in outline, we're going to talk about what a migration to modules even means. We're going to talk about why it was so challenging, but how I made it less painful. We're going to talk about how the migration actually worked under the hood, and we're going to talk about what that meant for us, how it went, and what's next or modules in TypeScript.

So getting back to basics here, what even are modules? I think there's a few different definitions one can come up for this, but I think the two most critical are the syntax itself. So that's import-export and the part where you make multiple files and import them between each other, but it's also the output format. So ESM like I've written below, CommonJS used in a Node ecosystem pretty heavily still, and plenty of other minor formats. When I'm talking about migrating TypeScript to modules, what I'm referring to is specifically this first one. So that's changing TypeScript to use the import and export syntax.

Now that begs the question, if TypeScript wasn't modules before, but didn't use import-export, what did it use? The answer is scripts. So in TypeScript, everything is either a script or a module. So if our files aren't modules, then they are scripts. We put all of our code into global namespaces. So you can see that we have parser.ts here, we define a function createSourceFile, export it, then in another file that declares the same namespace, we can use createSourceFile, and it all just works. You'll notice that we don't have to use ts. here to refer to that. If it's inside of the namespace we're currently working in, we get to refer to it implicitly. Now, namespaces were originally called internal modules, and you can sort of see why. They provide somewhat of the encapsulation, export, import that modules do, but differently. Now, when we go to emit these namespaces, they turn into plain objects and functions. So you can see on the left here that we have createSourceFile for parser.ts, it's defined as a function inside of a closure and because it's exported, it gets set to this ts namespace. Then later inside of program.ts, we define the ts namespace again. But when you go to createSourceFile, you notice that we get a ts. explicitly. Our implicit access became explicit.

2. Bundling and Imports in TypeScript

Short description:

Now, all of our code is in different files, but we can bundle them by using outfile and prepend. So, tsc has effectively been a bundle this whole time, although this option is being removed. If someone wants to import us, we can be clever by using namespaces. Namespaces have some upsides, but nobody writes code like this anymore. We want to have files that explicitly export and import each other.

Now, all of our code is in different files, but we can bundle them by using outfile and prepend. So you can see that inside of tsc's tsconfig, we set outfile to be tsc.js, and then we ask tsc to prepend all the contents of its dependent projects. Below, you can see all the code that the compiler defined, execute command line defined, they all get shoved on top of the file. And then all the code that happened to be in the tsc project.

So, tsc has effectively been a bundle this whole time, although we'll see later that this option is being removed. Now, if someone wants to import us, this is sort of interesting because we're global scripts. There's no imports or exports. But we can be clever here. What we can do is we can say if we're in a common JS context, that is, there is module and module exports, then we can just read our ts namespace as a value and set it to module.exports. This means that if someone loads us inside of a context that supports common JS, so Node, but also other bundlers, they'll see that this is a CGS module and it'll work as people expect. But if someone loads this into their web page by just using a script tag, they'll get a ts variable and it'll also work. Namespaces have some upsides. Because we're using namespaces, we don't have to write imports. Obviously, we're talking about adding imports. There's no imports at all before. When we add new code, we don't have to import it. If it's another file, we just use it. If we move code from one file to another, we don't have to change imports either. We also get bundling for free used by a TSC. But, nobody writes code like this anymore. This means that we don't get to dog food modules. If we want to test out things like Node Next resolution, auto imports, organized imports, all that good stuff, we can't do it in our own code base. We're also unable to use external tools that only handle imports and exports. So, if we want to say test for cycles between files, all those tools are expected to have imports present and we can't use them. We also need to maintain prepend. It turns out that nobody uses this feature except for TypeScript itself. So, it would be really great to remove from the product and say not maintain anymore. We want to have files that explicitly export and import each other. We have the same file before, but we have parser.tsx exporting create source file at the top level. And then in program.ts we import by name and use it.

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.
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.
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.

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.