Skip to main content

Setup

Installation

create a new app, you may choose one of the following methods:

http://localhost:3000
npm install -g typescript

tsconfig.json

  • TypeScript compiler a couple things here in this config file.
  • outDir is used the output directory name.
  • target this would be ES2015 language level.This includes the promise constructor, classes, right?. The reason is that before ES2015, we didn't have classes. what happens as we change the language level? Module resolution node, you don't have to worry about too much here, but just think of this as the conventional setting where things are in node modules.
  • moduleResolution It's the module module resolution you would expect if you weren't using TypeScript.And then here include, this is where we say what are we compiling,where is the source code? We're saying, everything in the source folder, compile everything in there. When "moduleResolution" is set to "node", it means that the compiler will use the same module resolution strategy as Node.js.
  • include where is the source code? We're saying, everything in the source folder, compile everything in there.
tsconfig.json
{
"compilerOptions": {
"outDir": "dist",
"target": "ES2015",
"moduleResolution": "node",
},
"include": ["src"]
}

Couple features here that will illustrate the difference between language levels here.

So there are a couple things in here that only work in ES 2015.There's async await, which only landed in ES 2017,and then I've thrown in a static private field,which only works in ES 2022.So what we hope to see here is that all of this kind of boils down to ES 2015.

What if you are using the the before ES2015 and you perform a export but its not working there?

we can't run it like this, right, with this export here.We'd have to make this a CJS module for node to just take it as is.Well, we have two options.We can make this an MJS file, if you're familiar with what those are.But let's make it a CJS file.

MJS File

  • MJS is these native JavaScript modules with this export keyword.
  • But let's make it the classic thing that node has been able to run for ages.
  • So we could go into our tsconfig and we could say, "module": "commonjs".
tsconfig.json
{
"compilerOptions": {
"outDir": "dist",
"target": "ES2015",
"moduleResolution": "node",
},
"include": ["src"]
}
  • So let's go back to our tsconfig.json and add an option here called declaration.
{
"compilerOptions": {
"outDir": "dist",
"target": "ES2022",
"moduleResolution": "node",
"module": "commonjs",
"declaration": true
},
"include": ["src"]
}

index.d.ts

  • This is a declaration file that TypeScript will generate for us.
  • This is a file that TypeScript will generate for us, and it will be in the same directory as the file that it's declaring.
  • Two file is generated when we compile the code of typescript into the js and d.ts file. The d.ts file is the declaration file.