basickarl
basickarl

Reputation: 40464

TypeScript importing module path

I have the following file:

myProjectRoot/src/server.ts

Inside this it has:

import testRouter from 'module/lib';

I have a library which exports a default value at:

myProjectRoot/src/module/lib.ts

My myProjectRoot/tsconfig.json file:

{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es6",
        "lib": [
            "es6"
        ],
        "sourceMap": true,
        "baseUrl": "./src/"
    },
    "exclude": [
        "node_modules"
    ]
}

I get the error: [ERROR] 15:50:42 Error: Cannot find module 'module/lib'

Upvotes: 1

Views: 1859

Answers (1)

Ruby Tunaley
Ruby Tunaley

Reputation: 371

You have two options here.

Use Relative Imports

This is the simplest option. Just specify relative paths when importing stuff.

import testRouter from './module/lib';

Set Up Import Aliases

You can edit your tsconfig.json so that it resolves the path you typed.

{
    "compilerOptions": {
        "baseUrl": "./src/",
        "paths": {
            "./*": ["./src/*"]
        }
    }
}

As we can see, TypeScript will now resolve the import properly.

Image of VS Code resolving the import correctly.

BEWARE: The above just tells the TypeScript compiler that paths can be resolved from src, but does not affect code emit. For example, the import statement still gets compiled to the following:

const lib_1 = require("module/lib");

This means that unless you have another build tool which can transform that require into a relative path, the import will not work at runtime even though TypeScript says it's okay.

Image of Node throwing due to bad module resolution.

Upvotes: 1

Related Questions