Step 1
First set up the package.json with the required dependencies by running npm install.
npm install --save-dev @babel/core @babel/preset-typescript
Step 2
Configure the TypeScript to JavaScript transforming code. In this example, you'll notice that I import babel to start with. Once that's done I provide a reference to my TypeScript code I want to transform. Then I configure the babel options, the Babel plugins I want to use. I set the options inline and ignore the other configuration file types. I did this because I wanted to keep this example short and sweet. Once I have the code and options, I call babel transform, which transforms the TypeScript to JavaScript. Then to finish it off, I use console output to render the output in the console.
// This file: index.js
// Run this file from the VSCode Launcher
// https://babeljs.io/docs/en/usage
// 1. npm install --save-dev @babel/core @babel/preset-typescript
// Import the node module.
const babel = require("@babel/core");
// Example of some typescript code.
let code = "const x: number = 0;";
// Provide the transform options, in particular the typescript plugin.
let options = {
plugins: ["@babel/plugin-transform-typescript"]
};
// Run the babel transform with typescript plugin.
let transformed = babel.transform(code, options);
// Output the typescript in Javascript.
console.log('Completed transformation: ', transformed.code);
// Outputs: $ Completed transformation: const x = 0;
Step 3
In this step, you can start the node processing the index.js and output the transformation to the console.
There are two ways you can execute this process. I like to use VSCode, so to do this, import the project root into VSCode, and then go tot he launcher and select 'Simple TypeScript Demo Transformation'. This will run Node and process index.js.
If you don't want to use VSCode, you can start the process from the terminal by running 'npm run start' from the base of the project.
That's it. There isn't much to transforming TypeScript to JavaScript using Node. There much more to be had in the docs, so stop by there and check out the other options.
Find the demo source here.
I hope that saves you some time in considering the Babel transform options.
No comments:
Post a Comment