Renaud
Renaud

Reputation: 4668

Side effects in import statements

Starting from the Basic Example in typescript-rest, I wanted to modularise by separating the HelloService class into its own file. Here it goes:

// 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!');
});

In short, I was expecting the 3 import statements:

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

to be equivalent in terms of side-effects. My original interpretation was that the file gets loaded and interpreted and so the @decorators do their magic (I don't know how they work under the hood) but apparently not.

Can someone point out the difference between these statements and explain the different outcomes?


Here is the doc on modules and module resolution

edit: I know it is also possible to explicitly register services with this library but that's not what I'm interested in here.

Upvotes: 1

Views: 3369

Answers (1)

Guilhermevrs
Guilhermevrs

Reputation: 2344

The explanation comes from https://www.typescriptlang.org/docs/handbook/modules.html#import-a-module-for-side-effects-only

This is part of optimisations done at transpiler level, that checks if no exports from a given import is used, it gets sacked out from the final bundle

Upvotes: 3

Related Questions