The resolution process depends primarily on the flag --moduleResolution
(found in tsconfig.json)
In NodeJS, there is a convention where directories are automatically resolved to a file named index
. This convention has extended to client-side development but remains just that - a convention. It is not specified by ECMAScript or AMD.
When you set --moduleResolution node
, TypeScript will follow this convention.
Additionally, if the flag --module
is set to commonjs
in tsconfig.json, this convention will be applied even without specifying --moduleResolution
.
This setting applies to both application code and dependencies in directories like node_modules
, jspm_packages
, and bower_components
.
While most suitable for CommonJS projects, using --moduleResolution node
can be beneficial for other module formats as well, facilitating dependency resolution and avoiding issues linked with the alternative classic
mode.
Note that loaders such as RequireJS and SystemJS won't automatically recognize this convention in your app code, so it's recommended to explicitly specify index files in module specifiers when importing your own app code.
Despite the emphasis on CommonJS, I prefer and recommend --moduleResolution node
, even though I don't use CommonJS, Webpack, or Browserify in the browser whenever possible.
In my case, I opt for SystemJS as the loader and JSPM as the package manager, yet I still find the node resolution scheme advantageous for easier dependency importing, particularly due to JSPM's auto configuration with the SystemJS loader.
Now, let's discuss --baseUrl
in relation to your situation.
If you're trying to import a local module like:
import * as modulename from "modulename";
and have set --module commonjs
and --baseUrl /
to treat the local module as a third-party package in preparation for splitting your codebase into a separate package - commendable planning, by the way!
However, if you intend to use CommonJS modules (which I recommend against for browser-only applications), make sure to set "baseUrl"
to "."
instead of "/"
. Note that tools like Native NodeJS require function lack support for baseUrl concepts originating from browser tooling. Nonetheless, Webpack does provide support for it.
To load modules part of your own source code with a non-relative or absolute URL module specifier, I suggest the following steps regardless of loader requirements:
- Set
"baseURl"
to "."
- Explicitly set
"moduleResolution"
to "node"
,
- Define
"module"
as "commonjs"
, "system"
, or "amd"
(avoid "umd"
).
- If not using
"commonjs"
under node, consider using "paths"
for advanced restructuring possibilities.