I'm trying to create a microservice using NodeJS, Hapi, and typescript. I have a basic route set up that was working, but I can't get my service created and imported using the directory structure that I want. That structure is basically:
/server.ts
/tsconfig.json
/packages.json
/Services/
/CarService.ts
/BoatService.ts
/Models
/Car.ts
/Boat.ts
/Tests
/Bundle
I'm trying to separate my models from my business logic. One of my services looks like:
module Services {
export class CarService {
saveCar(data: any): boolean {
return false;
}
}
}
but also looked like this:
class CarService {
saveCar(data: any): boolean {
return false;
}
}
export {CarService}
I've been trying to import this service into my server.ts
import CarService = Services.CarService;
let _carService = new CarService();
but it looked like this when I for the second version of carService
import * as _carService from './Services/CarService';
and I was trying to use the servcie like this:
server.route({
method: 'POST',
path: '/Cars/',
handler: function (request:any, reply) {
_carService.saveCar(request.payload); // the error is here
//_carService["saveCar"](request);
reply("we did it!");
}
});
The first method was giving me this error:
Property 'saveCar' does not exist on type 'typeof CarService'.
The second method compiles in visual code but is giving me this error:
ReferenceError: CarService is not defined
My tsconfig:
{
"compilerOptions": {
"module": "commonjs",
"moduleResolution": "node",
"outDir": "bundle",
"target": "es5",
"noImplicitAny": false,
"sourceMap": true,
"declaration": true
},
"filesGlob": [
"./**/*/.ts"
]
}
So obviously my modules aren't compiling right. I don't know if the error is related to the tsconfig module resolution strategy or the output directory. I've fiddled with those settings too. I know from reading the documentation that the module resolution strategies look in a /src/
folder first, but at one point I had a rootDirs' array in my tsconfig.json that pointed to my
/Models/and
/Services/` directories that I thought would solve that issue.
You can use
export default
inCarService.ts
, then import the class inserver.ts
:See also: