导入语句中的副作用

时间:2019-02-27 14:27:04

标签: typescript module decorator

typescript-rest中的Basic Example开始,我想通过将HelloService类分离到其自己的文件中进行模块化。在这里:

// hello-service.ts
import { Path, GET, PathParam } from "typescript-rest";

@Path("/hello")
export class HelloService {
  @Path(":name")
  @GET
  sayHello( @PathParam('name') name: string): string {
    return "Hello " + name;
  }
}
// index.ts
import * as express from "express";
import { Server } from "typescript-rest";

import './hello-service' // this works

// the following don't work
// import { HelloService } from './hello-service';
// import * as Foo from './hello-service'

// however they do work, but iif:
// new HelloService()
// new Foo.HelloService()

let app: express.Application = express();
Server.buildServices(app);

app.listen(3000, function() {
  console.log('Rest Server listening on port 3000!');
});

简而言之,我期待着3条进口声明:

import './hello-service'
import { HelloService } from './hello-service';
import * as Foo from './hello-service'

在副作用方面等效。我最初的解释是文件被加载和解释,因此@decorators发挥了魔力(我不知道它们是如何工作的),但显然没有。

有人可以指出这些陈述之间的区别并解释不同的结果吗?


这是modulesmodule resolution上的文档

编辑:我知道也可以explicitly register services使用该库,但这不是我对此感兴趣的地方。

1 个答案:

答案 0 :(得分:1)

说明来自https://www.typescriptlang.org/docs/handbook/modules.html#import-a-module-for-side-effects-only

这是在编译器级别进行的优化的一部分,该检查检查是否未使用给定导入的导出,将其从最终捆绑中解雇了

相关问题