How to compile typescript to javascript
How to compile typescript to javascript
Compile TypeScript with npm
Main Content
Author: James Edwards Published: 1/13/2021 Updated: 6/21/2021
Npm package.json scripts can be used to run various commands. Here, we will learn how to run the TypeScript compiler to generate JavaScript output from TypeScript source files. Before we start, make sure you have Node.js and npm installed.
TypeScript
In a new folder, create a file named script.ts. Then, add some sample code so we can test whether the JavaScript output is being generated properly.
TypeScript Compiler
In the same folder, create a new file named tsconfig.json. Here is the TypeScript official documentation for configuring tsconfig.json.
Your tsconfig.json file should look like this:
This configuration tells the TypeScript compiler to look for source files in the root of your project, where your tsconfig.json is located. For any TypeScript files it finds there, it will output the compiled JavaScript to a new folder named output.
package.json
In the same folder create a package.json file. Here is the npm official documentation on creating a package.json file.
Then, add the name and version properties required. You will also need to add a property called scripts. This property contains the script instructions that we will use to compile the TypeScript we created. In this case, our compilation script is named compile-typescript, and it runs the command tsc. This is the default TypeScript command, and it will utilize the tsconfig.json we created.
Your package.json file should look like this:
Now that package.json is created and the TypeScript compilation step is listed, we must save TypeScript as a dev dependency. This will give the npm task access.
npm Install TypeScript
After installing TypeScript, your package.json should look like this:
JavaScript
In a terminal window, navigate to the source code folder you created. Then, run the following command: npm run compile-typescript
Now, you should now see a new folder created named output, that contains one file named script.js. Notice how the output has defaulted to ES5 JavaScript, which is compatible with all major browsers.
Your script.js file should look like this:
Run Node.js Script
The script.js created as a result of running the «compile-typescript» command can now be run with Node.js. To do this another package.json script is added, which is named «start». The «start» script will run the node cli command which the path of the script.ts file is passed.
Run the start command by entering npm run start in a terminal window, and you should see the output «Hello World!» printed to the console.
Run npm Scripts Sequentially
To save time the «compile-typescript» and «start» commands can be combined into one command by modifying the start command to include this functionality.
Compiling TypeScript into JavaScript
Because browsers and Node.js process only JavaScript, you have to compile your TypeScript code before running or debugging it.
Compilation can also produce source maps that set correspondence between your TypeScript code and the JavaScript code that is actually executed.
IntelliJ IDEA comes with a built-in TypeScript compiler. By default, it outputs generated JavaScript files and sourcemaps next to the TypeScript file.
Compilation is invoked with the Compile actions from the TypeScript widget on the Status toolbar as described in Compile TypeScript code below.
Сompilation errors are reported in the TypeScript Tool Window. This list is not affected by changes you make to your code and is updated only when you invoke compilation again.
The tool window shows up only after you first compile your TypeScript code manually. After that the tool window is accessible via View | Tool Windows | TypeScript on the main menu or via the tool window bar.
Before you start
Make sure the TypeScript Language Service checkbox is selected.
Create a tsconfig.json file
By default, the built-in compiler does not create source maps that will let you step through your TypeScript code during a debugging session. The compiler also by default processes either the TypeScript file in the active editor tab or all TypeScript files from the current project.
With a tsconfig.json file, you can modify this default behavior to generate source maps and compile only files from a custom scope.
In the Project tool window, select the folder where your TypeScript code is (most often it is the project root folder) and then select New | tsconfig.json File from the context menu.
To override the default compilation scope, which is the entire project, add the files property and type the names of the files to process in the following format:
Compile TypeScript code
You can invoke compilation manually or have IntelliJ IDEA compile your code automatically every time the code is changed.
Alternatively, you can configure a build process, for example, with webpack, babel, or another tool.
Manual compilation
Click the TypeScript widget on the Status bar.
The widget is shown on the Status bar all the time after you have opened a TypeScript file in the editor.
Alternatively, select Compile TypeScript from the context menu of any open TypeScript file.
You can also press Ctrl+Shift+A and choose Compile TypeScript from the list.
To compile one file, open it in the editor, and select the path to the file from the list in the TypeScript widget.
Automatic compilation on changes
Open the Languages & Frameworks | TypeScript page of the IDE settings Ctrl+Alt+S and select the Recompile on changes checkbox.
Compiling TypeScript into JavaScript
Because browsers and Node.js process only JavaScript, you have to compile your TypeScript code before running or debugging it.
Compilation can also produce source maps that set correspondence between your TypeScript code and the JavaScript code that is actually executed.
PhpStorm comes with a built-in TypeScript compiler. By default, it outputs generated JavaScript files and sourcemaps next to the TypeScript file.
Compilation is invoked with the Compile actions from the TypeScript widget on the Status toolbar as described in Compile TypeScript code below.
Сompilation errors are reported in the TypeScript Tool Window. This list is not affected by changes you make to your code and is updated only when you invoke compilation again.
The tool window shows up only after you first compile your TypeScript code manually. After that the tool window is accessible via View | Tool Windows | TypeScript on the main menu or via the tool window bar.
Before you start
Make sure the TypeScript Language Service checkbox is selected.
Create a tsconfig.json file
By default, the built-in compiler does not create source maps that will let you step through your TypeScript code during a debugging session. The compiler also by default processes either the TypeScript file in the active editor tab or all TypeScript files from the current project.
With a tsconfig.json file, you can modify this default behavior to generate source maps and compile only files from a custom scope.
In the Project tool window, select the folder where your TypeScript code is (most often it is the project root folder) and then select New | tsconfig.json File from the context menu.
To override the default compilation scope, which is the entire project, add the files property and type the names of the files to process in the following format:
Compile TypeScript code
You can invoke compilation manually or have PhpStorm compile your code automatically every time the code is changed.
Alternatively, you can configure a build process, for example, with webpack, babel, or another tool.
Manual compilation
Click the TypeScript widget on the Status bar.
The widget is shown on the Status bar all the time after you have opened a TypeScript file in the editor.
Alternatively, select Compile TypeScript from the context menu of any open TypeScript file.
You can also press Ctrl+Shift+A and choose Compile TypeScript from the list.
To compile one file, open it in the editor, and select the path to the file from the list in the TypeScript widget.
Automatic compilation on changes
Open the Languages & Frameworks | TypeScript page of the IDE settings Ctrl+Alt+S and select the Recompile on changes checkbox.
Compiling TypeScript into JavaScript
Because browsers and Node.js process only JavaScript, you have to compile your TypeScript code before running or debugging it.
Compilation can also produce source maps that set correspondence between your TypeScript code and the JavaScript code that is actually executed.
PyCharm comes with a built-in TypeScript compiler. By default, it outputs generated JavaScript files and sourcemaps next to the TypeScript file.
Compilation is invoked with the Compile actions from the TypeScript widget on the Status toolbar as described in Compile TypeScript code below.
Сompilation errors are reported in the TypeScript Tool Window. This list is not affected by changes you make to your code and is updated only when you invoke compilation again.
The tool window shows up only after you first compile your TypeScript code manually. After that the tool window is accessible via View | Tool Windows | TypeScript on the main menu or via the tool window bar.
Before you start
Make sure the TypeScript Language Service checkbox is selected.
Create a tsconfig.json file
By default, the built-in compiler does not create source maps that will let you step through your TypeScript code during a debugging session. The compiler also by default processes either the TypeScript file in the active editor tab or all TypeScript files from the current project.
With a tsconfig.json file, you can modify this default behavior to generate source maps and compile only files from a custom scope.
In the Project tool window, select the folder where your TypeScript code is (most often it is the project root folder) and then select New | tsconfig.json File from the context menu.
To override the default compilation scope, which is the entire project, add the files property and type the names of the files to process in the following format:
Compile TypeScript code
You can invoke compilation manually or have PyCharm compile your code automatically every time the code is changed.
Alternatively, you can configure a build process, for example, with webpack, babel, or another tool.
Manual compilation
Click the TypeScript widget on the Status bar.
The widget is shown on the Status bar all the time after you have opened a TypeScript file in the editor.
Alternatively, select Compile TypeScript from the context menu of any open TypeScript file.
You can also press Ctrl+Shift+A and choose Compile TypeScript from the list.
To compile one file, open it in the editor, and select the path to the file from the list in the TypeScript widget.
Automatic compilation on changes
Open the Languages & Frameworks | TypeScript page of the IDE settings Ctrl+Alt+S and select the Recompile on changes checkbox.
3 Options to Compile Typescript to JS: Rollup, TSC, Babel
I recently took on a tech-debt related project at my last job which called for ripping out repeated code in 7(😲) repositories, that could be implemented as a reusable NPM package for importing and implementation. I had decided to code in Typescript. The question I had when it was time to publish was: “How am I going to bundle this code?”
As everything JavaScript and programming related, there’s more than 1 way to skin this cat. The options I considered:
I was using Parcel to develop my Provider component, so in theory I could just use their output, but I quickly eliminated this option since it was outputting a single file which I did not feel was ideal. I wanted to be able to ensure there was ability for tree-shaking and realized Parcel’s output is great for compiling code for outputting a final bundle. Not necessarily ideal for writing components.
This article will look at some of the benefits and drawbacks of Rollup, TSC, and Babel.
Some common setup files: tsconfig.json:
And a simplified version of package.json to include some scripts to run:
Rollup is a module bundler for JavaScript which compiles small pieces of code into something larger and more complex, such as a library or application.
Well, that description sure seems to hit the nail on the head! What’s nice about Rollup is that is also even includes logic for built-in treeshaking of my development code.
Setting up Rollup is slick with a simple rollup.config.js file.
What is ideal from this config file is that the typescript plugin has “options” to further configure what gets bundled up. For example, my actual code has myComponent.test.tsx test files. I do not want to ignore those files in the tsconfig.json but I also do not want my test files included as the build output for NPM. So the tsconfigOverride has a useful exclude option to achieve this goal.
Also notice the output array: Rollup has ability to export both ESModules and CommonJS (and AMD for those who need it). Have you seen in your package.json the fields for module and main and wondered what/when you need those? This is the time! When your NPM package is created, these 2 fields can be used to let your build/dev runner know where to find the contents of this package.
We will need to edit line 12 of the package.json like so:
You can see the important index.d.ts file which creates the declaration file so that when you import < Button >from ‘reusable-thing’ the module is correctly resolved, and (Bonus) you will avoid the Linting error: error TS2307: Cannot find module ‘moduleA’.
That was pretty easy. In case you were wondering why I added the cjs export type, it’s because the project was unable to resolve my module as an es type. I never did get to the bottom of “why”, unfortunately. To use cjs export types, I had to tweak a few things when using the commonjs plugin.
Rollup is nice because of the plugin’s available. Similar to the webpack environment. Need some non-js file copied? There’s probably a plugin.
Next up is using the Typescript tsc command. There are a few opinions, including in the typescript docs, about whether to use this built in command to compile or just have it generate the declaration files. Rather than say which is “better”, this article is just to provide some options. The nice part of using tsc is that there’s really no other libraries to install.
Let’s run the command and see what happens. First we need to update the npm script on line 12 of package to npm run tsc
Then we run it. 🤔 That’s interesting. The terminal looks ok. But build output is empty!? Oh right. We need to change the tsconfig flag of noEmit to false so that the compiler emits an output.
Run build again. Now, the output directory looks a little different from the rollup version:
The most obvious change is that the excluded stories.js files are now here. Is this OK? Maybe…maybe before packaging your npm module, you can update the npmignore file to exlude them 🤷♂.
It’s something to consider as a possible extra step & file to keep the output as simple as possible.
Note that the original tsconfig has declaration set to true. That is why we have our d.ts files without any additional changes.
What about non-JS files, such as svg, json, jpg? Well they do not get copied over by TSC automatically. You will need to have another npm script added to your command that runs after.
Finally, let’s take a look at Babel for this. Right off the bat, Babel has a similar compiling limitation to be aware of, similar to TSC above, in that it only looks as “js” files. Any non-js files will require the same “copy” script as above.
A new babel.config.js file can be created. You may need to download some additional plugins for @babel for this to work correctly.
Also, let’s update our package.json script on line 12 to:
And we can run npm run build again. Here is the output of build :
Notice immediately that there is no *.d.ts file or anything related to “types” for use after this is packaged up by NPM. This is by design from babel. Afterall, it’s just a transpiler:
The downside to using babel is that you don’t get type checking during the transition from TS to JS.
The workaround on this is to add a tsc command with a modified tsconfig that only emits declaration files. The emitDeclarationTrue flag would need to be set in this case.
I hope this comparison helps. Each of these options are viable. It truly depends on your setup and requirements.
For what it’s worth, I ended up using Rollup in my Provide library.
However, in the other TS project within a legacy “lock step microfront end” application, I implemented a build command like this:
We run tsc to have a type checking before transpiling to a pure JS bundle. In other apps we need to include a copy script so that those non-js assets are included.
Источники информации:
- http://www.jetbrains.com/help/idea/compiling-typescript-to-javascript.html
- http://www.jetbrains.com/help/phpstorm/compiling-typescript-to-javascript.html
- http://www.jetbrains.com/help/pycharm/compiling-typescript-to-javascript.html
- http://medium.com/@lucksp_22012/3-options-to-compile-typescript-to-js-rollup-tsc-babel-3319977a6946