English 中文(简体)
Including .hbs handlebars file in Typescript transpile
原标题:

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!

问题回答

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",




相关问题
store data in memory with nestjs

I am trying to persist some data in my nestjs server so I can then use that data in my client app through http requests. I have created a products.service.ts file with the function getAllData() that ...

React Hook Form Error on custom Input component

I am having a problem when I use react hook form + zod in my application, in short the inputs never change value and I get the following error in the console: Warning: Function components cannot be ...

Updatable promises using proxy in JavaScript

EDIT: I ve updated this question, and the old question is moved here. A POC can be found on this jsfiddle or the snippet below GOAL: The goal here is to make or rather simulate a promise that can be ...

热门标签