简体   繁体   中英

require for modules in nodejs with typescript

Following the code in server.ts:

const express = require('express');
const athletesRouter = require('./src/routes/athletesRouter');

Running node server.ts in the console, throws:

Error: Cannot find module './src/routes/athletesRouter'

If I change server.ts to server.js and athletesRouter.ts to athletesRouter.js, then everything works fine.

This is my tsconfig.json:

{
  "compilerOptions": {
    "noImplicitAny": true,
    "esModuleInterop": true,
    "target": "esnext",
    "moduleResolution": "node",
    "allowSyntheticDefaultImports": true,
  },
}

And this is .babelrc (although I am not sure if this is relevant):

{
  "presets": [
    [
      "@babel/preset-typescript",
      {
        "targets": {
          "node": "current"
        }
      }
    ]
  ]
}

What am I missing?

A solution for this is to install ts-node and then run in the console ts-node server.ts This npm package has to be installed globally in order to use that command.

BELOW EXTRA INFORMATION TO EXPAND ON THIS TOPIC

There are two scenarios:

  • Development enviroment: nodemon can be used to reload the server while changing code. Its --exec command can be used to run ts-node without the need to transpile .ts into .js

  • Production enviroment: .ts code has to be transpiled into .js . This can be done with tsc command from typescript. After that, use node command from nodejs.

An example of this two-scenarios approach can be found below in this package.json where two scripts are used:

"scripts": {
    "startDevelopment": "nodemon --exec ts-node server.ts",
    "startProduction": "tsc && node server.js"
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM