Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript does not load handlebar files

I have the following directory structure :

src
|- server
  |- myServer.ts
  |- views
    |- myView.hbs
dist
|- server
  |- myServer.js

Note that there is no views folder in the dist folder (where the js sources compiled from typescript are). This is a problem because when I ask for the ../views/selectCoin.hbs from the javascript, there is nothing.

How do I export *.hbs files to javascript when typescript is compiled ?

like image 898
Moebius Avatar asked Jan 27 '18 23:01

Moebius


1 Answers

To tell handlebars where the views are you can configure it like this

app.set('view engine', 'hbs');
app.set('views', path.join(__dirname, '../../src/server/views'));
app.engine('hbs', exphbs({
    defaultLayout: 'index',
    extname: 'hbs',
    layoutsDir: path.join(__dirname, '../../src/server/views/layouts'),
    partialsDir: path.join(__dirname, '../../src/server/views'),
}));

So it will look for views in the src folder.


Another option is to use ts-node instead of node. With it you don't need to compile your project and you don't need a dist folder, and you can configure it to look directly from where you are:

app.set('view engine', 'hbs');
app.set('views', path.join(__dirname, 'views'));
app.engine('hbs', exphbs({
    defaultLayout: 'index',
    extname: 'hbs',
    layoutsDir: path.join(__dirname, 'views/layouts'),
    partialsDir: path.join(__dirname, 'views'),
}));

If you want to copy the views to the dist folder you could:

  • make a shell script to copy files
  • copy-webpack-plugin if using webpack
  • copy files with gulp if using gulp
like image 186
BrunoLM Avatar answered Sep 29 '22 09:09

BrunoLM