Search code examples
javascriptnode.jstypescriptbabeljstsc

Trying to babel either JavaScript OR TypeScript files for use in Node environment


Our node environment requires that our JavaScript files be babeled. This is easy enough.

The difficult part is that we have .js, .jsx, .ts, .tsx files and this won't change.

Is there anything I could do to get the TypeScript files converted into JavaScript, and then have all the .js/.jsx files go through babel?

My current command:

nodemon app.js --exec babel-node --presets env,stage-2,react

I know that I need TypeScript to be converted somewhere in there.

Any ideas?

Node version: 8.11.1


Solution

  • With babel 7 you can use the typescript preset. You still need typescript to do the actual type checking, just the compilation to js will now be done by babel.

    Here's what a simple setup might look like:

    1. npm install --save-dev @babel/preset-typescript

    Update the rest of the toolchain to babel 7 too (e.g. babel-cli to @babel/cli @babel/core, babel-preset-env to @babel/preset-env etc.)

    1. Add "noEmit": true to your tsconfig.json. This ensures typescript only does type checking and doesn't output js.

    2. Add --extensions '.js,.jsx,.ts,.tsx' to your command.

    So your command becomes:

    nodemon app.js --exec babel-node --presets @babel/env,@babel/stage-2,@babel/react,@babel/typescript --extensions '.js,.jsx,.ts,.tsx'