Home > Mobile >  Typescript project setup
Typescript project setup

Time:02-02

I am pretty new to Typescript and I having trouble starting the typescript project setup. Have done all the installations required and ran very simple programs and works perfect. Need help in setting up a project in a specific requirement.

Have a project structure like:

myProject
    -node_modules
    -src
        -controller
            -MyController.ts
        -service
            -MyService.ts
        -domain
            -MyDomain.ts
        -exception
            -MyException.ts
        -constants
            -MyConstant.ts
        app.ts
    package.json
    tsconfig.json
    yarn.lock

I need to run this project which should call app.ts first which will inturn call my controller and then my service to display Hello World.

What code will I write in app.ts, MyController.ts and MyService.ts?

I know this is a big ask. But I dont have a learning curve now to learn ts. Have to learn it on the go. Any sample project or code which help me pick pace soon.

Thanks for all the help in advance.

UPDATE:

package.json:

{
  "name": "myProject",
  "version": "1.0.0",
  "description": "",
  "main": "src/app.js",
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@types/express": "^4.17.13",
    "@types/node": "^17.0.14",
    "express": "^4.17.2",
    "nodemon": "^2.0.15",
    "ts-node": "^10.4.0",
    "typescript": "^4.5.5"
  },
  "scripts": {
    "dev": "nodemon --config nodemon.json src/app.ts",
    "start": "node src/app.js",
    "build": "tsc --myProject ."
  }
}

tsconfig.json:

{
  "compilerOptions": {
    "target": "es2016",
    "module": "commonjs",   
    "esModuleInterop": true, 
    "forceConsistentCasingInFileNames": true, 
    "strict": true,  
    "skipLibCheck": true 
  }
}

CodePudding user response:

Do you want to create an Web API ? If yes you can use NestJS, it's a complete framework which offer you the possibility to create Web API in typescript on NodeJS Runtime. With it you will also be able to use dependency injection with typescript decorators.

I hope it will help ;)

CodePudding user response:

You need to create a exported class or method to be called. Place this in your MyController.ts file:

export class MyController {
    public static execute() {
        return 'MyController Hello World'
    }
}

Then you can call it from app.ts like this:

import { MyController } from './controller/MyController'

console.log(MyController.execute())
  •  Tags:  
  • Related