0

When I use require in my NodeJS + Typescript app I must add index.ts file to the url otherwise I get en error Cannot find module './api', e.g.

const api = require('./api/index.ts') - works

const api = require('./api') - not working

My package.json:

  "dependencies": {
    "@types/express": "^4.16.1",
    "cors": "^2.8.5",
    "express": "^4.16.4",
    "mongoose": "^5.5.5",
    "morgan": "^1.9.1",
    "ts-node": "^8.1.0",
    "ts-node-dev": "^1.0.0-pre.32",
    "tslint": "^5.16.0",
    "typescript": "^3.4.5"
  }
0

4 Answers 4

1

This could be the result of a few things. Your package.json has little bearing on how TypeScript resolves relative imports/requires.

Check your target, module and moduleResolution compiler options in your tsconfig.json file. More specifically, module should be set to "commonjs" (for Node.js applications) and moduleResolution should be set to "node"

Read more about it here.

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

Comments

1

TypeScript source files must be compiled to JavaScript files, before to be executed by Node.js.

For example with: npx tsc.

Comments

1

require is not the default importing format when you are using typescript so might not resolve sometimes, try using import * as api from './api' instead

Comments

0

indeed there were 2 issues:

  • using ES5 syntax
  • not compiling TS files

So instead of using require I've changed everything to import and also needed to add ts-node to my script, like : nodemon --watch '*.ts' --exec 'ts-node' server.ts

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.