1

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'

9
  • I think you can just put src/ if the tsconfig is on the root already Commented May 8, 2019 at 13:59
  • @MikeTung I would prefer not to do so. Commented May 8, 2019 at 14:00
  • @MikeTung Why would that make a difference? Commented May 8, 2019 at 14:53
  • 1
    Maybe this article could help. Commented May 8, 2019 at 14:55
  • @Paleo I was looking for this. I have seen it work using paths Commented May 8, 2019 at 15:00

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.