2

I've been trying to use handlebars in my Typescript node.js project by importing it through the readFileSync fs method, however when the project is transpiled into Javascript the .hbs file does not appear in the dist folder and the code can not find the handlebars template

I have been importing the handlebars template in a .ts file

import { handlebarsData } from "./Types/HandlebarsData";
import { readFileSync, writeFileSync } from "fs";
import Handlebars from "handlebars";

const newFile = (data: handlebarsData) = {
const template = readFileSync("./template.hbs");
const compiledTemplate = Handlebars.compile(template);
    const renderedTemplate = compiledTemplate(data);
    writeFileSync(`${data.name}.html`, renderedTemplate);
};
export default newClass;

And I have .hbs files in my include in the tsconfig.json

{
  "compilerOptions": {
    "module": "commonjs",
    "esModuleInterop": true,
    "target": "es6",
    "moduleResolution": "node",
    "sourceMap": true,
    "outDir": "dist"
  },
  "lib": ["es2015"],
  "include": ["src", "src/**/*.hbs"],
  "exclude": ["node_modules"]
}

However it is not being added to the dist folder on transpile, causing the read file sync to fail

I do not have any dependencies that remove files. My only dependencies are typescript, handlebars, and ts-node.

Thanks so much for the help!

1 Answers1

0

You can use gulp to it.

First, you should install gulp:

npm install gulp gulp-shell --save-dev

Then create a gulpfile.js file in the root of your project and the templates source folder to dist/:

const gulp = require('gulp');
const shell = require('gulp-shell');

// adjust to your path
gulp.task('copy-templates', shell.task('cp -R src/templates dist'));

gulp.task('default', gulp.series('copy-templates'));

Then add the following line to your .tsconfig exclude templates folder from your ts compilation:

"exclude": ["src/templates"]

Run Gulp to trigger the copy task:

npx gulp

PS: you can add it to your build command to make the process easier, e.g:

"build": "rm -rf dist/ && tsc && npx gulp",