ts-node icon indicating copy to clipboard operation
ts-node copied to clipboard

ts-node cannot find module

Open tedcurrent opened this issue 9 years ago โ€ข 34 comments

I have two files:

  • src/app/index.ts
  • src/config.ts

Within index.ts:

import { getConfig } from "config";  
getConfig();

Within config.ts:

export const getConfig = () => console.log("hello world!");

I have a tsconfig.json file:

{
  "compilerOptions": {
    "outDir": "./ts-build/",
    "module": "commonjs",
    "moduleResolution": "node",
    "baseUrl": "src",
    "target": "es5"
  }
}

Running ts-node ./src/app/index.ts throws me: Error: Cannot find module 'config'. Setting moduleResolution to classic doesn't change anything.

Versions:

"ts-node": "^3.3.0",
"typescript": "^2.5.2"

Any ideas if this is a ts-node issue, typescript issue or did I do something wrong?

tedcurrent avatar Sep 11 '17 08:09 tedcurrent

This https://github.com/TypeStrong/ts-node/issues/1012

SephReed avatar Apr 22 '20 17:04 SephReed

ts-node always works from pwd. you need to set basedir in tsconfig.json and work with tsconfig-paths.

dbwodlf3 avatar Nov 25 '21 06:11 dbwodlf3

ts-node always works from pwd. you need to set basedir in tsconfig.json and work with tsconfig-paths.

That is exactly what I did and I am still having that problem. Not sure if the problem lies on the fact that I'm using require to import a file that then uses import. Here is my tsconfig:

{
  "compilerOptions": {
    "outDir": "./dist",
    "jsx": "react",
    "allowJs": true,
    "esModuleInterop": true,
    "target": "es6",
    "baseUrl": "./src",
    "module": "esnext",
    "moduleResolution": "Node",
    "sourceMap": true,
    // NOTE: this is only temporary until we actually can add all typescript types!
    "skipLibCheck": true,
    "paths": {
      "react": ["../node_modules/react"],
      "redux": ["redux/*"],
      "testUtils": ["testUtils"],
      "spring/*": ["../../spring/*"],
      "spring": ["../../spring/src"]
    },
    "lib": ["es2020", "DOM"]
  },
  "include": ["./src/**/*", "./types"],
  "exclude": ["node_modules"],
  "ts-node": {
    "compilerOptions": {
      "paths": {
        "ukStrings": ["./src/ukStrings.ts"]
      },
      "module": "CommonJS",
      "target": "es2017"
    }
  }
}

As you can see, I have a path specified for ts-node. However, when I require a file require(fullPathToFile) that then imports ukStrings I get a can not compile error, telling me that it can't find the ukStrings file.

danielo515 avatar Nov 26 '21 13:11 danielo515

You could use the module-alias package as described in https://dev.to/larswaechter/path-aliases-with-typescript-in-nodejs-4353

cprcrack avatar Mar 25 '22 16:03 cprcrack

Hi,

I'm having the same issue from the first post, long story short I'm converting a nodejs app to typescript, I run the app with:

ts-node-esm .\\src\\server.ts

This is my tsconfig.json

  "compilerOptions": {
    /* Docs: [https://www.typescriptlang.org/tsconfig](https://www.typescriptlang.org/tsconfig) */
    "target": "ES2020",
    "module": "ESNext",
    "outDir": "bin",
    "rootDir": "src",
    "strict": true,
    "noImplicitAny": false,
    "strictNullChecks": true,
    "checkJs": true,
    "allowJs": true,
    "moduleResolution": "node",
    "types": ["node"],
    "lib": ["es6"],
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "allowUnreachableCode": true,
    "useUnknownInCatchVariables": false // TypeScript 4.4+ only!
  },
  "include": ["src/**/*.ts", "src/**/*.js"],
  "exclude": ["node_modules", "<node_internals>/**"],
  "esm": true
}

Any help would be great!

alainosorio avatar Nov 30 '22 16:11 alainosorio

I met the problem: Error: Cannot find module '@app/lib/prisma_client', and I add the following code in the tsconfig.json:

{
  "ts-node": {
    // Do not forget to `npm i -D tsconfig-paths`
    "require": ["tsconfig-paths/register"]
  }
}

then re-run ts-node src/index.ts, everything is good now! reference: paths and baseUrl and the full tsconfig.json is here:

{
  "compilerOptions": {
    "target": "es2016",
    "module": "commonjs",
    "baseUrl": "./src",
    "paths": {
      "@app/*": ["*"]
    },
    "outDir": "./dist",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true
  },
  "include": ["src/**/*.ts"],
  "exclude": ["node_modules"],
  "ts-node": {
    "require": ["tsconfig-paths/register"]
  }
}

blingblingdev avatar Dec 07 '22 08:12 blingblingdev

thx๏ผŒthis question tried me tolong.

thomas-void0 avatar Apr 23 '23 02:04 thomas-void0

I had pretty much the same issue as the OP, but using esm. I didn't get anywhere with the solutions in the comments here but this blog post did help.

Specifically, adding "experimentalSpecifierResolution": "node" in my ts-config under ts-node resolved my issue.

Full ts-config:

{
  "compilerOptions": {
    "target": "ES2019",
    "lib": [
      "es2019",
      "DOM"
    ],
    "module": "ESNext",
    "declaration": true,
    "strict": true,
    "strictNullChecks": true,
    "noImplicitThis": true,
    "alwaysStrict": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": false,
    "experimentalDecorators": true,
    "strictPropertyInitialization": false,
    "isolatedModules": true,
    "typeRoots": [
      "./node_modules/@types"
    ],
    "resolveJsonModule": true,
    "esModuleInterop": true,
    "moduleResolution": "node"
  },
  "ts-node": {
    "esm": true,
    "experimentalSpecifierResolution": "node",
    "transpileOnly": true
  }
}

dwil618 avatar May 10 '23 09:05 dwil618

For anyone struggling with ts-node or ts-node-dev modify your package.json with ts-node-dev -r tsconfig-paths/register --poll src/app.ts

sagargulati avatar May 30 '23 17:05 sagargulati

Thank you dwil618

It works in windows node v18

"ts-node": { "esm": true, "experimentalSpecifierResolution": "node", "transpileOnly": true }

byleese avatar Jun 22 '23 03:06 byleese

i know this is an old issue, but i recently stumbled onto it myself. I believe i found a workaround:

Relevant configuration:

directory structure:

/

/dist/src/foo/...
/dist/src/foo.js

/dist/test/foo/integration/...
/dist/test/foo/unit/...

/src/foo/...
/src/foo.ts

/test/foo/integration/...
/test/foo/unit/...

THE MAIN OFFENDER: package.json:

{
    "imports": {
        "#src/*": "./dist/src/*",
        "#test/*": "./dist/test/*"
    },
}

tsconfig.json:

{
    "include": [
        "src/**/*",
        "test/**/*"
    ],
    "exclude": [
        "node_modules/**/*",
        "dist/**/*"
    ],
    "compilerOptions": {
        "rootDir": ".",
        "outDir": "./dist",
        "baseUrl": ".",
        "paths": {
            "#src/*": [ "src/*" ],
            "#test/*": [ "test/*" ]
        },
    }
}

Problem synopsis:

  • tsconfig-paths/register can't handle this particular case.
  • ts-node uses imports: { ... } from package.json rather then paths from tsconfig.json.
  • if "imports": { "#src/*": "./dist/src/*" } then NODE_ENV=dev code stops working. aka ts-node, nodemon, etc stops working, because /dist/ dir by definition doesn't exist in NODE_ENV=dev mode.
  • if "imports": { "#src/*": "./src/*" } then NODE_ENB=prod code stops working. aka node . bc *.js files reside in /dist/src/ dir. node simply doesn't see /src/dist/**/*.js code with path aliases directed to /src/ dir. Not to mention /src/ dir is populated with *.ts files.

Workaround:

  1. Create a 2nd package.json file in /dist/package.json:
{
    "imports": {
        "#src/*": "./src/*",
        "#test/*": "./test/*"
    },
}
  1. Rewrite original package.json in /package.json:
{
    "imports": {
        "#src/*": "./src/*",
        "#test/*": "./test/*"
    },
}

Explanation:

  • NODE_ENB=dev code resides in /src/ dir as *.ts files.
  • NODE_ENB=prod code resides in /dist/src/ dir as *.js files.
  • import: { ... } in /package.json configures how ts-node will resolve path aliases in /src dir, aka the NODE_ENB=dev code.
  • import: { ... } in /dist/package.json configures how node will resolve path aliases in /src/dist dir, aka the NODE_ENB=prod code.

I do not know if this workaround is foolproof. I can imagine problems when trying to publish a package with multiple package.json files. But haven't tested it yet.

Please leave a like if you found this workaround helpful ๐Ÿ™‡๐Ÿ™‡๐Ÿ™‡๐Ÿ™‡

Patryk-B avatar Oct 01 '23 22:10 Patryk-B

What I actually discovered was that I have to have the environment variable NODE_PATH set to match the baseUrl also. I ended up running the following: NODE_PATH=./src ts-node ./src/app/index.ts.

that's exactly it! solved it for me, tks

hems avatar Dec 02 '23 15:12 hems

Thank you dwil618

It works in windows node v18

"ts-node": { "esm": true, "experimentalSpecifierResolution": "node", "transpileOnly": true }

@byleese what is this , where do you put this?

tombohub avatar Mar 05 '24 21:03 tombohub

tsconfig.json

{
  "compilerOptions": {
    "target": "es2017" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
    "lib": [
      "es2017",
      "esnext.asynciterable"
    ] /* Specify a set of bundled library declaration files that describe the target runtime environment. */,
    "module": "commonjs" /* Specify what module code is generated. */,
    "rootDir": "." /* Specify the root folder within your source files. */,
    "moduleResolution": "Node" /* Specify how TypeScript looks up a file from a given module specifier. */,
    "baseUrl": "./" /* Specify the base directory to resolve non-relative module names. */,
    "paths": {
      "@src/*": ["./src/*"],
      "@prisma/*": ["./prisma/*"]
    } /* Specify a set of entries that re-map imports to additional lookup locations. */,
    "typeRoots": [
      "src/types/libraries/",
      "node_modules/@types"
    ] /* Specify multiple folders that act like './node_modules/@types'. */,
    "resolveJsonModule": true /* Enable importing .json files. */,
    "declaration": true /* Generate .d.ts files from TypeScript and JavaScript files in your project. */,
    "sourceMap": true /* Create source map files for emitted JavaScript files. */,
    "outDir": "./dist" /* Specify an output folder for all emitted files. */,
    "importHelpers": true /* Allow importing helper functions from tslib once per project, instead of including them per-file. */,
    "allowSyntheticDefaultImports": true /* Allow 'import x from y' when a module doesn't have a default export. */,
    "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */,
    "forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,
    "strict": true /* Enable all strict type-checking options. */,
    "useUnknownInCatchVariables": true /* Default catch clause variables as 'unknown' instead of 'any'. */,
    "skipLibCheck": true /* Skip type checking all .d.ts files. */
  },
  "include": ["src/**/*", ".env"],
  "exclude": ["node_modules", "src/http", "src/logs", "src/tests"],
  "ts-node": {
    "require": ["tsconfig-paths/register"]
  }
}

package.json

{
  "name": "server",
  "scripts": {
    "dev": "ts-node src/index.ts",
    "build": "tsc && tsc-alias",
    "start": "node dist/src/index.js"
  },
  "devDependencies": {
    "@types/node": "^20.12.12",
    "ts-node": "^10.9.2",
    "tsc-alias": "^1.8.10",
    "tsconfig-paths": "^4.2.0",
    "typescript": "^5.4.5"
  },
  "version": "1.0.0",
  "main": "index.ts",
  "license": "MIT"
}



xreider avatar May 20 '24 13:05 xreider