1 minute read

Item 60: Use allowJs to Mix TypeScript and JavaScript

• Don’t spend too much time getting your code perfectly typed with JSDoc.

Remember that the goal is to convert to .ts!

Advertisement

For a small project, you may be able to convert from JavaScript to TypeScript in one fell swoop. But for a larger project this “stop the world” approach won’t work. You need to be able to transition gradually. That means you need a way for TypeScript and JavaScript to coexist. The key to this is the allowJs compiler option. With allowJs, TypeScript files and JavaScript files may import one another. For JavaScript files this mode is extremely permissive. Unless you use @ts-check (Item 59), the only errors you’ll see are syntax errors. This is “TypeScript is a superset of JavaScript” in the most trivial sense. While it’s unlikely to catch errors, allowJs does give you an opportunity to introduce TypeScript into your build chain before you start making code changes. This is a good idea because you’ll want to be able to run your tests as you convert modules to TypeScript (Item 61). If your bundler includes TypeScript integration or has a plug-in available, that’s usu‐ally the easiest path forward. With browserify, for instance, you run npm install --sav-dev tsify and add it as a plug-in:

$ browserify index.ts -p [ tsify --noImplicitAny ] > bundle.js

Most unit testing tools have an option like this as well. With the jest tool, for instance, you install ts-jest and pass TypeScript sources through it by specifying a

jest.config.js like:

module.exports = { transform: { '^.+\\.tsx?$': 'ts-jest', }, };

If your build chain is custom, your task will be more involved. But there’s always a good fallback option: when you specify the outDir option, TypeScript will generate pure JavaScript sources in a directory that parallels your source tree. Usually your existing build chain can be run over that. You may need to tweak TypeScript’s Java‐Script output so that it closely matches your original JavaScript source, (e.g., by speci‐fying the target and module options). Adding TypeScript into your build and test process may not be the most enjoyable task, but it is an essential one that will let you begin to migrate your code with confidence.

This article is from: