• TypeScript With Babel: A Beautiful Marriage
  • By Matt Turnbull
  • The Nuggets translation Project
  • Permanent link to this article: github.com/xitu/gold-m…
  • Translator: zsky
  • Proofreader: Xionglong58, brilliantGuo

Working with TypeScript is easier than ever, thanks to an official year-long collaboration between the TypeScript and Babel teams: TypeScript Plugin for Babel (@babel/preset- TypeScript). This article gives you four reasons why TypeScript and Babel are a perfect match, and teaches you to upgrade to TypeScript step by step in 10 minutes.

Huh? What? Why is that?

I didn’t understand the necessity of this preset at first.

Aren’t Babel and TypeScript two very different things? How does Babel handle TypeScript type checking? TypeScript already prints ES5 code like Babel, so what’s the point? Doesn’t merging Babel with TypeScript complicate things?

After a few hours of research, my conclusion is:

TypeScript and Babel are a beautiful marriage.

Let me tell you why.

1) You already use Babel (or should)

You fall into one of these three categories:

  1. You already use Babel. If not used directly, your Webpack configuration will put*.jsFiles are provided to Babel (as is the case with most scaffolding, includingcreate-react-app)
  2. Uses TypeScript, but not Babel. For that, consider adding Babel to your Arsenal, as it offers many unique features. Read on to learn more!
  3. You don’t use Babel? It’s time to get started.

Write modern JavaScript without breaking anything

Does your JavaScript code need to run in an older browser? No problem, Babel will transform the code without any problems. Use the latest and greatest features and don’t worry.

TypeScript compilers have similar capabilities, which can be achieved by setting target to ES5 or ES6. But the Babel configuration improves this with babel-preset-env. Instead of locking down a specific set of JavaScript features (ES5, ES6, etc.), you can list the environments you need to support:

"The targets" : {" browsers ": [" last 2 versions", "safari > = 7"], "node" : "6.10"}Copy the code

Babel uses compat-table to check the JavaScript functionality to be converted and to polyfill for those specific target environments.

Take a moment to admire the genius who named this project ‘Compat-table’.

Create-react-app uses an interesting technique: it is compiled with the latest browsers during development (for speed) and with a wider range of browsers in production (for compatibility). Beautiful.

Babel is super configurable

Want JSX? The Flow? TypeScript? Babel can handle it by installing a plug-in. There are a number of official plug-ins, mainly covering the upcoming JavaScript syntax. There are also many third-party plug-ins: Improve Lodash imports, Enhance console.log, or Strip console.log. Find more information in the awesome- Babel list.

Be careful, though. If the plug-in changes the syntax significantly, TypeScript may not be able to parse it. For example, the much anticipated Optional Chaining Proposal proposes a Babel plugin:

@babel/plugin-proposal-optional-chaining

Unfortunately, TypeScript doesn’t understand this updated syntax.

Take it easy, there’s another option…

Babel macro

Do you know Kent C Dodds? He created a game-changing Babel plugin: babel-plugin-Macros.

Instead of adding plug-ins to the Babel configuration file, you can install the macro as a dependency and import it into your code. When Babel is compiling, macros start and modify the code as needed.

Let’s look at an example. It uses IDX. macro to resolve pain points until the optional chaining proposal is passed:

import idx from 'idx.macro';

const friends = idx(
  props,
  _ => _.user.friends[0].friends
);
Copy the code

Compile as follows:

const friends =
  props.user == null ? props.user :
  props.user.friends == null ? props.user.friends :
  props.user.friends[0] = =null ? props.user.friends[0] :
  props.user.friends[0].friends
Copy the code

Macros are fairly new, but are quickly gaining popularity. Especially with create-React-app V2.0. The CSS in JS is overridden: Styled – JSX, Styled – Components and emotion. Webpack plugins are being ported: raw-loader, URl-loader, and filesize-loader. There are more listed in awesome-babel-macros.

Here’s the best part: Unlike the Babel plug-in, all Babel macros are TypeScript compatible. They can also help reduce runtime dependencies, avoid some client-side calculations, and catch errors ahead of time at build time. Check out this post for more details.

Better console.log: scope.macro

2) It is easier to manage a compiler

TypeScript needs its own compiler — it provides amazing type checking capabilities.

Depressing days (before Babel 7)

Linking two independent compilers (TypeScript and Babel) together is not easy. The compilation process becomes: TS > TS Compiler > JS > Babel > JS (again).

Webpack is often used to solve this problem. Adjust the Webpack configuration to feed *.ts to TypeScript, and then feed the result to Babel. But which TypeScript loader do you use? Two popular options are TS-loader and awesome-typescript-loader. The readme. md for awesome-typescript-loader mentions that it can be slower for some workloads and recommends using TS-Loader plus HappyPack or Threadloader. Readme. md of TS-loader is recommended to combine fork-ts-checker-webpack-plugin, HappyPack, Thread-loader, and/or cache-loader.

Ah. Not at all. This is where most people get overwhelmed and put TypeScript in the “too hard” basket. I don’t blame them.

Sunny days (with Babel 7)

Wouldn’t it be nice to have a JavaScript compiler? Whether your code has ES2015, JSX, TypeScript, or crazy customizations – the compiler knows what to do.

I just described Babel. Thick-skinned.

By allowing Babel to act as a single compiler, you don’t need to use some complicated Webpack magic to manage, configure, or combine two compilers.

It also simplifies the entire JavaScript ecosystem. They only need to support Babel, not syntax checking, test runners, build systems, and scaffolding that support different compilers. Then, configure Babel to meet your specific needs. Say goodbye to TS-Node, TS-Jest, TS-karma, create-react-app-typescript, and use Babel support instead. Support for Babel is everywhere, check out the Babel setup page:

Babel covers your needs.

3) Faster compilation

Warning! Here’s some shocking news that you might want to sit down and listen to.

How does Babel handle TypeScript code? It deletes it.

Yes, it removes all TypeScript, converts it to “regular” JavaScript, and continues happily in its own way.

It sounds ridiculous, but this approach has two big advantages.

First advantage: ️⚡️ lightning fast ⚡ ⚡.

Most Typescript developers experience long compile times in development/monitor mode. You’re writing code, saving a file, and… It comes… And then… Finally, you see your changes. Oops, one wrong word, fix, save, and… Ah. It’s just annoyingly slow and takes away your momentum.

It’s hard to blame the TypeScript compiler, which does a lot of work. It scans the type definition files (*.d.ts) including node_modules and makes sure your code is using them correctly. This is why many people separate Typescript type checking into a separate process. However, the Babel + TypeScript combination still provides faster compilation thanks to Babel’s advanced caching and single-file emission architecture.

So if Babel strips TypeScript code, what’s the point of writing TypeScript? This brings a second advantage…

4) Check for type errors only when you are ready

You change some code together to quickly come up with a solution to see if your idea is valid. TypeScript screams at you when you press the save button:

“No! I can’t compile this! Your code has problems in 42 different files!”

Yes, you know it doesn’t work anymore. You might also break some unit tests. But you’re just experimenting at this point. The constant need to ensure that all code is type-safe at all times is maddening.

This is the second advantage of Babel stripping TypeScript code at compile time. You write code, save it, and compile (very quickly) without checking type safety. Keep trying solutions until you’re ready to check the code for errors. This workflow allows you to stay focused while coding.

So how do you check for type errors? Add an NPM run check-types script that calls the TypeScript compiler. I adjusted my NPM test command to first check the type and then continue to run the unit test.

It’s not a perfect match

According to the post, there are four TypeScript features that don’t compile in Babel because of their single-file emission architecture.

Don’t worry, it’s not that bad. TypeScript warns about these problems when the isolatedModules flag is enabled.

1) Namespaces.

Solution: Don’t use them! They are out of date. Use the industry standard ES6 module (import/export) instead. The tsLint rule is recommended to ensure that namespaces are not used.

2) Use < newType >x syntax to convert types.

Solution: use x as newtype.

3)Const enumeration.

It’s a shame. Now you need to use regular enumerations.

4) Traditional style import/export syntax.

Example: import foo = require(…) And export = foo.

In all my years of working with TypeScript, I’ve never seen anything like this. Who codes this way? Stop!

Ok, I’m ready to try Babel and TypeScript!

Taken by rawpixel.com

Let’s get to work! It should only take about 10 minutes.

I’m assuming you set up Babel 7. If not, refer to the Babel Migration guide.

1) Rename the.js file to.ts

Suppose your file is in/SRC:

find src -name "*.js" -exec sh -c 'mv "$0" "${0%.js}.ts"'{};Copy the code

2) Add TypeScript to Babel.

Install some dependencies:

npm install --save-dev @babel/preset-typescript @babel/plugin-proposal-class-properties @babel/plugin-proposal-object-rest-spread
Copy the code

Add the following to your Babel configuration file (.babelrc or babel.config.js) :

{
  "presets": [
    "@babel/typescript"]."plugins": [
    "@babel/proposal-class-properties"."@babel/proposal-object-rest-spread"]}Copy the code

TypeScript has some additional features that Babel needs to know about (through the two plug-ins listed above).

By default, Babel looks for.js files, which unfortunately is not configurable in the Babel configuration file.

If you use Babel CLI, add –extensions ‘.ts’

If you use Webpack, add ‘ts’ to the resolve.Extensions array.

3) Add the “check-types” command.

Add this to package.json:

"scripts": {
  "check-types": "tsc"
}
Copy the code

This command simply calls the TypeScript compiler (TSC).

Where does TSC come from? We need to install TypeScript:

npm install --save-dev typescript
Copy the code

To configure TypeScript (and TSC), we need the tsconfig.json file in the root directory:

{
  "compilerOptions": {
    // Target latest version of ECMAScript.
    "target": "esnext",
    // Search under node_modules for non-relative imports.
    "moduleResolution": "node",
    // Process & infer types from .js files.
    "allowJs": true,
    // Don't emit; allow Babel to transform files. "noEmit": true, // Enable strictest settings like strictNullChecks & noImplicitAny. "strict": true, // Disallow features that require cross-file information for emit. "isolatedModules": true, // Import non-ES modules as default imports. "esModuleInterop": true }, "include": [ "src" ] }Copy the code

To complete.

Ok, setup is done. Now run NPM run check-types (listening mode: NPM run check-types — –watch) and make sure TypeScript is happy with your code. You may find errors that you didn’t know existed. That’s a good thing! This guide to migrating from Javascript will also give you some help.

Microsoft’s typescript-Babel-Starter guide contains additional setup instructions, including installing Babel from scratch, generating type definitions (D.ts) files, and using it with React.

What about syntax checking?

Use tslint.

Update (February 2019) : Using ESlint! The TypeScript team has been focusing on ESLint integration since January. Eslint is easy to configure, thanks to the @typesript-ESLint project. For reference, check out my super ESLint configuration, which includes TypeScript, Airbnb, Prettier, and React.

Babel + TypeScript = beautiful combination

Photo by Akshar Dave

Babel is the only JavaScript compiler you need. It can be configured to handle anything.

There is no need to fight with two competing JavaScript compilers. Simplify your project configuration and take advantage of Babel’s amazing integration with syntax checkers, test runners, build systems, and scaffolding.

The combination of Babel and TypeScript compiles quickly and allows you to focus on coding, checking types only when you’re ready.

Prediction: TypeScript usage will rise

According to the latest Stack Overflow developer survey, JavaScript is the most popular language and TypeScript is number 12. This is still a great achievement for TypeScript, beating Out Ruby, Swift, and Go.

I predict TypeScript will be in the top 10 next year.

The TypeScript team is working hard to roll it out. This Babel Preset is a one year collaboration, and their new focus is on improving ESLint integration. It’s a smart move — leveraging the functionality, community, and plug-ins of existing tools. Developing competitive compilers and syntax checks is a waste of effort.

The path to TypeScript is already paved; we just need to adjust the configuration of our favorite tools. Barriers to entry have been broken down.

With the popularity of VS Code, developers have set up a great TypeScript environment. Auto-completion while writing code will bring tears of joy.

It’s also now integrated into Create-React-App V2.0, bringing TypeScript to users who download 200,000 times a month.

If you’re putting off using TypeScript because it’s too hard to set up, that’s no longer an excuse. It’s time to give it a try.

If you find any mistakes in your translation or other areas that need to be improved, you are welcome to the Nuggets Translation Program to revise and PR your translation, and you can also get the corresponding reward points. The permanent link to this article at the beginning of this article is the MarkDown link to this article on GitHub.


The Nuggets Translation Project is a community that translates quality Internet technical articles from English sharing articles on nuggets. The content covers Android, iOS, front-end, back-end, blockchain, products, design, artificial intelligence and other fields. If you want to see more high-quality translation, please continue to pay attention to the Translation plan of Digging Gold, the official Weibo, Zhihu column.