TypeScript is supertype of JavaScript, or for easier understanding, TypeScrirpt is JavaScript with syntax for types. It is now developed by Microsoft. It is a lovely programming language which tries to “patch” the flaws of JavaScript. TypeScript adds static typing to JavaScript, and as a static typing programming language it can be used to catch any errors before deployment (well, hopefully).
TypeScript compilation result is JavaScript. Documentation is very complete and details, but one thing that I found confusing is how TypeScript treats import. In the documentation, import statement instructed to be written like this for relatif TypeScript file:
import blablabla ...... from './path/to/lib'
Unfortunately, when you do this, the compilation result will be error if you try to execute the JavaScript file. For example, I have this kind of structure:
.
├── db
│ └── dbinit.ts
└── index.ts
From index.ts
, I want to use dbinit.ts
, so, according to TypeScript documentation, this should be written (provided that sql is the result of a const inside dbinit.ts):
import sql from './db/dbinit'
This will be an error when I try to run index.js
as the result of TypeScript compilation since TypeScript will not compile that line into JavaScript import. The result still the same:
import sql from './db/dbinit'
The workaround is simple. When compile TS to JS for module import, always put the future result for import statement. Example:
import sql from './db/dbinit.js'
DO NOT DO THIS:
import sql from './db/dbinit'
Inside db path, put this file:
src/db/
└── dbinit.ts
in dir db
, do not put dbinit.js
but put dbinit.ts
. The file dbinit.js
in the source code above is the future compilation result. If we don’t do this, there will be an error since TS will not compile import sql from './db/dbinit'
to import sql from './db/dbinit.js'
.
Although TypeScript documentation uses the latter (without extension), it won’t work. This has been the source of debates: