Using TypeScript with Webpack

“TypeScript” is a great language that powers up “JavaScript” and in this post, we’ll see how to ingrate it with “webpack”. If you’re not comfortable with “webpack”, consider reading this post. Start by initializing our web application:

yarn init -y

Then, install the following packages:

yarn add webpack webpack-cli typescript ts-loader -D

Next, add the following “scripts” in the “package.json” file to be able to run “webpack”:

Now, let’s create two files. “./src/student.ts” that contains the following code:

And the file “./src/index.ts” with the following content:

If we run “webpack” now via the command:

npm run build

It won’t work because, by default, “webpack” will try to find the file “./src/index.js” as entry point and won’t find it. This means that we need to create a “webpack.config.js” file to define the entry point by ourselves:

Only doing that won’t be enough to make “webpack” understand “TypeScript”. Indeed, if you try to run the command again, the error will this time say that we need an appropriate loader to load “ts” files, which is why we installed the package “ts-loader”. Let’s modify our “webpack.config.js” to handle these files:

We define “resolve.extensions” in order to be able to import “TypeScript” files without specifying their file extensions (for example: the line 1 of the “./src/index.ts” file).

Unfortunately, this is not yet enough for “webpack” to be able to use “TypeScript”. Indeed, now we need to create a “tsconfig.json” file to configure the “TypeScript” compilation. So create this file at the root of your project with the minimal configuration:

As you probably know, this option specifies that the “TypeScript” will have to be compiled as “ES5 JavaScript” code. You can now run the “build” command to compile your application. Normally, you shouldn’t get any error and have a “./dist/main.js”.

1 Response

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.