Integration Compiler Options
Learn how to configure TypeScript compiler options to include JavaScript files and generate distributable JavaScript files.
We'll cover the following...
There are a few compiler options that we can configure in order to help with the integration of JavaScript and TypeScript. These options will allow us to include JavaScript files within the same project as TypeScript files, as well as allowing us to do some type checking on JavaScript files.
We are also able to generate declaration files from our TypeScript code if we are building libraries for general consumption.
We will explore these compiler options.
The allowJs
and outDir
options
The default TypeScript compilation configuration, as seen in the tsconfig.json
file, will generate JavaScript files in the same directory as the source TypeScript files.
The outDir
compilation option is used to specify a different output directory for the generated JavaScript:
{"compilerOptions": {"target": "es5","module": "commonjs","outDir": "./dist","strict": true,"esModuleInterop": true,"skipLibCheck": true,"forceConsistentCasingInFileNames": true}}
Here, we have a tsconfig.json
file that has specified the outDir
property on line 5 for generated JavaScript, which is set to the ./dist
directory. When the TypeScript compiler is invoked, all of the generated JavaScript will be written to the ./dist
directory instead of being generated in the same directory as the source TypeScript files.
This compile option is generally used in order to create a distributable version of the generated JavaScript. By writing output to a separate directory, we are able to keep the TypeScript source files away from the generated JavaScript and create a version of our project that is just pure JavaScript. Having a distributable version of the generated JavaScript also allows us to run post-compilation steps, such as minification, uglification, or bundling.
In a TypeScript-only project, in other words, where all of the source files are written in TypeScript, this is a convenient and viable option.
Unfortunately, if we are mixing JavaScript source files with TypeScript source files in the same project, only the TypeScript-generated JavaScript will be written to this directory.
If our project includes both JavaScript source files as well as ...