简体   繁体   English

如何通过不使用新关键字运行NodeJS项目

[英]How to Run NodeJS Project With Class By Not Using new Keyword

I am developing a NodeJS project by using TypeScript. 我正在使用TypeScript开发NodeJS项目。 But I can't figure out how to run app.ts file by using class. 但我无法弄清楚如何使用类运行app.ts文件。

How to run Root class without new keyword ? 如何在没有new关键字的情况下运行Root类? That is the point. 这就是重点。

App.TS App.TS

// Express
import { application as app } from 'express';

// Controllers
import { UserController } from './controllers/user.controller'

export class App {
  constructor(userController: UserController) {
    console.log("App is running");
    console.log("UserController url path is : ", userController.getUrlPath);
  }

  run(): void {
    app.listen(3000, function () {
      console.log('App is running on port 3000!');
    });
  }
}

Root.TS Root.TS

import { App } from "../app";

export class Root {
    constructor(application: App) {
        application.run();
    }
}

How to run Root class without new keyword ? 如何在没有new关键字的情况下运行Root类? That is the point. 这就是重点。

Because it has to get instances of parameters of its constructor with dependency injection. 因为它必须通过依赖注入来获取其构造函数的参数实例。

Compiler start code : 编译器启动代码:

ts-node-dev --respawn --transpileOnly ./app/root.ts

This code tries to run root.ts file's code. 此代码尝试运行root.ts文件的代码。 There is a Root class but there is no created object of class. 有一个Root类,但没有创建类的对象。 So, there is no runnable class or method. 因此,没有可运行的类或方法。

You cannot "execute" a .ts file with Node.JS, you need to compile it first in JavaScript. 你不能用Node.JS“执行”.ts文件,你需要先用JavaScript编译它。 Use the typescript module to do this: npm i -s typescript 使用typescript模块执行此操作: npm i -s typescript

Then run the command tsc in your terminal. 然后在终端中运行命令tsc

To execute TS files you can simply install and use ts-node , it has all the same behaviour as a normal node but will transpile any file needed. 要执行TS文件,您只需安装和使用ts-node ,它具有与普通节点相同的行为,但会转换所需的任何文件。

This way you won't even need to transpile your code before running it. 这样,您甚至无需在运行代码之前转换代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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