Home > Net >  How to create/config a NodeTS(TypeScript NodeJS) project?
How to create/config a NodeTS(TypeScript NodeJS) project?

Time:07-29

I am trying to create and run a simple TypeScript NodeJS project. Followings are my codes:

server.ts:

import express from 'express';

const app = express();
const PORT = 3000;

app.listen(PORT , ()=>{
    console.log('Server is listening on port $PORT');
});

tsconfig.json:

{
  "compilerOptions": {
  
    "target": "esnext",                                  /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */

    "module": "commonjs",                                /* Specify what module code is generated. */
    "rootDir": "./src",                                  /* Specify the root folder within your source files. */
    "moduleResolution": "node",                       /* Specify how TypeScript looks up a file from a given module specifier. */

    "outDir": "./build",                                   /* Specify an output folder for all emitted files. */
    "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. */
    "skipLibCheck": true                                 /* Skip type checking all .d.ts files. */
  }
}

package.json:

{
  "name": "back",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon build/server.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@types/express": "^4.17.13",
    "express": "^4.18.1",
    "mongoose": "^6.5.0",
    "nodemon": "^2.0.19"
  }
}

When I try npm start I get the following error message:

> [email protected] start       
> nodemon build/server.js

[nodemon] 2.0.19
[nodemon] to restart at any time, enter `rs`      
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json        
[nodemon] starting `node build/server.js index.js`
node:internal/modules/cjs/loader:936
  throw err;
  ^

Error: Cannot find module 'C:\Users\A\\Test\back\index.js'
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
    at Function.Module._load (node:internal/modules/cjs/loader:778:27)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
    at node:internal/main/run_main_module:17:47 {
  code: 'MODULE_NOT_FOUND',
  requireStack: []
}
[nodemon] app crashed - waiting for file changes before starting...

CodePudding user response:

You've set your entry file to be index.js in package.json, so nodemon is trying to run both server.js and index.js, which does not exist. The simplest way you can solve this − provided that you've transpiled your TS files with tsc, for example − is to change the entry point main in package.json to build/server.js.

So what you have to do:

  1. Install typescript to be able to transpile you code:
npm install typescript
  1. Before running npm start, you have to make sure your code is transpiled, that is, "compiled" to vanilla JavaScript, so add this script to your package.json:
{
  "scripts": {
    // ...
    "build": "tsc"
  }
}
  1. Update main in package.json to be build/server.js.
  2. Run npm run build then finally npm start.

Done! Your server will start.


My tips before the answer update:

Also, creating a configuration file for nodemon (nodemon.json) will make things much simpler for you, take a look at the docs.

Lastly, if you're new at this, I recommend taking a look at some ready-made tsconfig bases from this repo, in special this one for Node 16.

CodePudding user response:

I modified my tsconfig.json file as following and it worked:

{
  "name": "back",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon src/server.ts"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@types/express": "^4.17.13",
    "express": "^4.18.1",
    "mongoose": "^6.5.0"
  },
  "devDependencies": {
    "nodemon": "^2.0.19",
    "ts-node-dev": "^2.0.0",
    "typescript": "^4.7.4"
  }
}

The created changes are in these lines:

"main": "index.js" To "main": "server.js"

"start": "nodemon build/server.js" To "start": "nodemon src/server.ts"

  • Related