Angular-RU/universal-starter

Problem with using typescript in server code

hofa77 opened this issue · 5 comments

when I want to use type script as server code I get Error

my .ts code


`
import * as express from 'express';

class PostController {
public router;
public path = '/Post';

constructor() {
    this.router = express.Router();
    this.initRoutes();
}

public initRoutes() {
    this.router.get(this.path, this.getPosts);
}

getPosts(request: express.Request, response: express.Response) {
    response.send('Posts list')
}

}

export default PostController;
`

and when I wun " npm run ssr"
I get this error
can you please help me

`
ERROR in ./ServerCode/post.controller.ts 4:11
Module parse failed: Unexpected token (4:11)
You may need an appropriate loader to handle this file type, currently no loader
s are configured to process this file. See https://webpack.js.org/concepts#loade
rs
|
| class PostController {

public router;

| public path = '/Post';
|
@ ./server.ts 73:0-57 74:21-35
`

and I am using it in the server.ts like this

`import PostController from './ServerCode/post.controller'

app.use('/postUser', PostController);
`

I am also facing this issue. Any solution for this?

I had to import my routes with require instead of import

Can you try:

const PostController = require('./ServerCode/post.controller');

app.use('/postUser', PostController);

btw. you need also to export your class in post.controller.ts

In my route it looks like this:

class Api {
  constructor() {
    this.app = express();
    this.mountRoutes();
  }
  public app;
  // Access this API route using {GET} and {POST} localhost:443/api/...
  private mountRoutes(): void {
    const router = express.Router();
    router.post('/dummy', (req, res) => {
      console.log(req.body);
    });
    module.exports = router;
  }
}

export default new Api().app;

I recommendation separate scripts for universal and backend