There are two methods for achieving this goal.
Option 1: Installing in the node_modules
directory
In this scenario, the library is installed in the consumer's node_modules
folder and utilizes Node module resolution.
Node module resolution configuration involves the TypeScript compiler searching for the node_modules
directory within your workspace. If there is an exported code that matches your import statement in this directory, the compiler can resolve it with a short import statement. More information on this configuration can be found here.
If the library is published and deployed to a registry such as https://registry.npmjs.org/ or an Artifactory repository, you can add the deployed library to the consumer's package.json
as a dependency and install it using npm install
. This will ensure that the library is placed in the node_modules
directory. By configuring the compiler options in the tsconfig.json
file with Node module resolution, the TypeScript compiler can effectively resolve the short import statement.
This approach assumes that the library has been deployed to a registry. If the library is only available locally, tools like the CLI of install-local can aid in installing the library in the local node_modules
without requiring deployment. Alternatively, there is another method outlined in the next section.
Option 2: Referencing the published source directly from the dist
directory
In the consumer project's tsconfig.json
, you can specify locally published modules in the paths
under the compilerOptions
settings. This allows the TypeScript compiler to resolve dependencies from these configured paths. Therefore, there is no need to install the dependency in the node_modules
directory to use the short import statement; the compiler will locate them based on the specified paths.
For example, if we have a library named my-lib
, the structure of the dist
folder would appear as follows:
dist
-->my-lib
---->{all the published files of my-lib}
-->my-app
---->{all the published files of my-app}
In this scenario, a sample tsconfig.json
for the consumer would look like this:
{
"compileOnSave": false,
"compilerOptions": {
"baseUrl": "./",
"outDir": "./dist/out-tsc",
"sourceMap": true,
"declaration": false,
"module": "es2015",
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"importHelpers": true,
"target": "es5",
"typeRoots": [
"node_modules/@types"
],
"lib": [
"es2018",
"dom"
],
"paths": {
"my-lib": [
"dist/my-lib"
],
"my-lib/*": [
"dist/my-lib/*"
]
}
}
}
In the paths
section, both my-lib
and my-lib/*
entries are required. my-lib
can be used in the short import statement, like so:
import { MyLibModule } from 'my-lib';
The paths defined in the tsconfig point to the published library in the dist
directory.
Note that exports need to be manually structured in the index.ts
file of the package.