Nodejs is used to create javascript backend environment. With typescript, javascript becomes validated, easier to be maintained thanks for a more structured codebase. However, as typescript gets popular, its integration and changes create some frictions for the developers.
In this article, we describe a problem that consists in allowing import in nodejs to work intuitively and with typescript.
this problem is described in depth in some articles https://devblogs.microsoft.com/typescript/announcing-typescript-4-7/#type-in-package-json-and-new-extensions. But, I will add my takes from it and more importantly, I will add the steps how I came to a solution for this problem.
simply put, when we import a javascript file, we have become used to add the name of the file and leave the extension out of the import.
The problem is that a typescript environment requires the typescript files to be compiled in javascript files. And whilst this is a separate step with the import process, it gives some issues for the import to work correctly.
At the moment, the most practical solution is to add the full name of the javascript file and that works well. But typescript is a bit of a purist world and for this reason, the developers want to come to a point where the codebase is neat and maintainable. To achieve this, having no extension is a benefit since it prevents the file extension to be set incorrectly.
During the explanation of this issue, 2 new words are essential to be understood well:
- what is an ES module?
- what is a commonJS module?
Reference: https://www.knowledgehut.com/blog/web-development/commonjs-vs-es-modules
CommonJS are javascript files that only implement synchronous javascript methods
ES module instead do implement asynchronous javascript methods