Module declaration in TS
Mohammad Jawad (Kasir) Barati
Posted on November 15, 2024
Here we learn how to write a high-quality Typescript declaration file. So you're coding in ReactJS and wanna importi an SVG file but your IDE/tsc is complaining.
[ts] cannot find module './logo.svg'
This is the time to turn to Stackoverflow for a quick copypaste solution.
But let's hold on and try to understand these files and what they do for us for a second.
What is a module?
In TS/JS we have had a lot of approaches to modularizing our apps written in TS/JS. Currently what reign supreme is ESM (AKA ES modules, ES6 modules). We usually know them with their syntax:
So to answer the original question, in TS/JS in line with ECMAScript 2015, any file containing a top-level import
or export
is considered a module.
And if one do not have any top-level import
or export
:
- They are available everywhere.
- They are treated as scripts.
Why use modules?
No global namespace pollution anymore. This implies that:
- Modules are executed within their own scope.
- We need to explicitly export whatever we meant to export.
- Consumer can import from a different module what they've exposed to others.
Named exports and default exports
Module resolution
In TS module resolution is the process of taking a string from the import
or require
statement, and determining what file that string refers to.
In TS we have two strategies:
- Classic:
- The default one.
- The
compilerOptions.module
is not"CommonJS"
. - Included for backwards compatibility.
- Node:
- Replicates how NodeJS works in CommonJS mode.
- Additional checks for
.ts
and.d.ts
files.
BTW we have tons of places tht we might intentionally or unintentionally change it (moduleResolution
, baseUrl
, paths
, rootDirs
).
moduleResolution
- Controls how TS resolves module specifiers (those string literals in
import
/export
/require
statements) to files on disk. - Should be set to match the module resolver used by the target runtime or bundler.
For example if you're building your app to utilize ESM (the compiled version is using ESM) then you need to choose "NodeNext"
in your compilerOptions.module
.
- As long as we are using a relative path + file extension TS can resolve it (e.g.
import {} from "./a.js"; // ✅ Works in every moduleResolution
). - If you're planning on compiling your app to use ESM, then you need to specify the extension of the files and cannot go extensionless (e.g.
import {} from 'a.mjs';
). - You can also import a directory which is expected to have an
index.ts
file.
Note: if inside that dir
you have a package.json
. Then TS use its main
and types
to pick up on its types.
paths
So basically it re-maps import
s to lookup location*s* relative to the baseUrl
if set, otherwise to the tsconfig
file. The most common use case for this are path aliases:
{
"compilerOptions": {
"module": "esnext",
"moduleResolution": "bundler",
"paths": {
"@shared/*": ["./src/shared"]
}
}
}
Caution
This does not mean anything for the runtime. Meaning your dear bundler or compiler needs to take care of bundling them together correctly. And if your path is pointing to somewhere that does not exists then your app will crash when it is being executed by NodeJS.
Tip
Instead of this you can utilize
package.json
'simports
(AKA Subpath imports).
baseUrl
- Base directory from which to resolve bare specifier1 module names
- Has higher priority than lookups from
node_modules
. - No longer required to be set when using
paths
.
rootDirs
- Many "virtual" directories acting as a single root.
- Then compiler can resolve relative module
import
s within these "virtual" directories, as if they were merged into one directory.
Compiled JS
To affect the emitted JS output we can modify:
-
compilerOptions.target
:- Determines which JS features are converted to run in older JavaScript runtimes.
- Dictated by our application requirements, things like on which browser/NodeJS/Electron I am gonna run this compiled TS code.
-
compilerOptions.module
:- which module system runtime will use.
- Use
"nodenext"
for modern NodeJS projects. It reads the nearestpackage.json
file and uses its"type"
value to decide whether it should go for CommonJS or ESM. - Use
"esnext"
for when you're gonna bundle it with a bundler.
Back to the main topic
So we wanna import .graphql
file or other extension that TS do not have any idea of what they look like (it cannot resolve their types). So now TS knows what an imported svg, graphql, or other files will look like.
ref.
-
Bare specifier: a module name in an
import
statement that is NOT a relative or absolute path. These are typically names of packages in your project'snode_modules
or other configured locations. ↩
Posted on November 15, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.