How can I include pug templates in compiled typescript?

Viewed 650

My nodejs based application uses Pug for rendering; specifically, i set the view engine and then set the view directory (which lives inside of the src directory that all other source lives in.

app.set('view engine', 'pug');
app.set('views', __dirname + '/views');
[...]
res.render('login')

This works correctly for the development version, which simply runs and interprets the typescript file that the above code is in. However, I would like to compile to javascript in production, and have the following (seemingly standard) typescript configuration:

{
    "compilerOptions": {
        "target": "esnext",
        "module": "CommonJS",
        "esModuleInterop": true,
        "skipLibCheck": true,
        "forceConsistentCasingInFileNames": true,
        "outDir":"./dist",
        "rootDir": "./src"
    },
    "$schema": "https://json.schemastore.org/tsconfig",
    "display": "Recommended",
    "files": ["src/index.ts"],
}

Which reflects the directory structure of my code:

the directory structure of my source code.

Unfortunately, this fails to work when the application is compiled and ruins index.js; it cannot find the .pug files in /dist/views: Error: Failed to lookup view "posts" in views directory "/app/dist/views"

I understand the error message, but not how to fix the problem. Should I be copying the templates to that folder as part of the build process? Should I be invoking them in another way that the compiler can 'understand' and include? Is compiling typescript to javascript simply an obsolete build step entirely?

2 Answers
app.set('views', __dirname + '/views');

This line configures Express to load the templates from the views folder, located in the same place as the executed script (which would be /dist in that case).

The options are:

  • Configure the build to copy the templates to /dist/views.
  • Change the path settings, and put for example all .ts sources in /src, view templates in /views and configure app.set('views', __dirname + '/../views'); so it would be seen from /src as well as from /dist.
  • Or skip the build step altogether and use ts-node, it can execute your .ts files directly.

edit: Bundling template scripts with the compiled .js file would only make sense or be useful if the bundle had to be sent to a Web browser, but as Express applications typically run server-side and not in a browser, Express does not support such a handling.

Copy non-typescript files to outDir


I was facing the same problem but there is just a simple solution to get all non-ts files in your build folder

here the package I used Typescript-cp

{
  //...
  "scripts": {
    "start": "tsc -w & tscp -w",
    "build": "tsc && tscp"
  },
  //...
}

it will copy all your non-ts files in the build folder but you can specify which one to copy I think read Docs

Related