3 Ways to Implement TypeScript Into Your Project

Isovera Staff
Isovera
Published in
2 min readJan 7, 2019

TypeScript is great -you get static type-checking, ECMAScript features yet to be supported by browsers, and excellent IntelliSense features.

So how do we go about implementing this awesome language into one of our projects? Well there’s a few ways! First, though, we have to setup our configuration file!

1. TypeScript Compiler

The simplest way to compile your TypeScript code is to use the default compiler. All you have to do to get this to work is run:

npm install --save typescript

Then in your package.json

{
...
"scripts": {
...
"build-ts": "tsc",
}
...
}

At this point all you have to do is run:

npm run build-ts

The compiled code should appear in your dist directory.

2. Gulp

An alternative to the default compiler is to use gulp! To get gulp to compile your TypeScript code, start by installing the gulp and gulp-typescript modules.

npm install --save-dev gulp gulp-typescript

You’ll also need to update your package.json:

{
...
"scripts": {
...
"gulp": "gulp",
}
...
}

You can then setup a gulp task to build the TypeScript code.

const gulp = require('gulp');
const ts = require('gulp-typescript');
gulp.task('default', () => {
return gulp.src('src/**/*.ts')
.pipe(ts({
noImplicitAny: true,
}))
.pipe(gulp.dest('dist'));
})
;

To build your TypeScript code, run npm run gulp and you’re good to go!

In order to use your tsconfig.json file, setup your gulpfile.js as such:

const gulp = require('gulp');
const ts = require('gulp-typescript');
const tsProject = ts.createProject('tsconfig.json');gulp.task('default', () => {
return tsProject.src()
.pipe(tsProject())
.pipe(gulp.dest('dist'));
})
;

3. Webpack

Install webpack and ts-loader. Note that you must also have the typescript package installed for this method to work.

npm install --save-dev webpack webpack-cli ts-loader

In your webpack.config.js file:

module.exports = {
mode: "development",
devtool: "inline-source-map",
entry: "./src/Rectangle.ts",
output: {
filename: "bundle.js"
},
resolve: {
extensions: [".ts", ".tsx", ".js"]
},
module: {
rules: [
{ test: /\.tsx?$/, loader: "ts-loader" }
]
}
};

Finally, in package.json:

{
...
"scripts": {
...
"webpack": "webpack",
}
...
}

You can then compile your code by running npm run webpack.

You’ll notice that instead of compiling all of your TypeScript files individually into JavaScript files like the default compiler or gulp, Webpack builds one bundle.js file. Depending on what you’re trying to do, this could prove to be incredibly useful for building browser-executable code.

That’s All, Folks!

Any one of these methods only takes a moment to implement and has you using TypeScript in no time whatsoever! Happy coding!

This article was originally published by Mae Bechdol on our Isovera blog.

--

--