Home > Article > Web Front-end > Module declaration in TS
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.
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:
No global namespace pollution anymore. This implies that:
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:
BTW we have tons of places tht we might intentionally or unintentionally change it (moduleResolution, baseUrl, paths, rootDirs).
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.
Note: if inside that dir you have a package.json. Then TS use its main and types to pick up on its types.
Learn more here.
So basically it re-maps imports 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:
[ts] cannot find module './logo.svg'
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's imports (AKA Subpath imports).
To affect the emitted JS output we can modify:
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's node_modules or other configured locations. ↩
The above is the detailed content of Module declaration in TS. For more information, please follow other related articles on the PHP Chinese website!