How to use Handlebars in Angular 12
Asked Answered
W

1

3

I used to be able to use Handlebars in Angular 11 but since I updated to Angular 12 I'm getting the following errors:

./node_modules/handlebars/lib/index.js:25:2-9 - Warning: Critical dependency: require function is used in a way in which dependencies cannot be statically extracted
./node_modules/handlebars/lib/index.js:23:38-45 - Error: Module not found: Error: Can't resolve '.' in '/node_modules/handlebars/lib'

I'm importing Handlebars like

import * as handlebars from 'handlebars';

I have tried to add Handlebars to the angular.json as following but nothing seems to be working.

"node_modules/handlebars/dist/handlebars.min.js"
Wampum answered 24/8, 2021 at 15:40 Comment(4)
What are you trying to do with handlebars specifically in relation to angular? The question is a bit confusing as angular has its own templating system for rendering data for component templates.Leporine
@AlexanderStaroselsky I'm using handlebarsjs to validate user input for email templates which have to be written in handlebars.Wampum
You need to share more code. It's not clear what angular is doing in your application, how that data is provided to the server and/or handlebars template. With angular forms you can validate input before submitting the form or sending HTTP request. Perhaps show your angular form and what you are trying to validate.Leporine
That being said, your import seems fine when just adding handlebars as a dependency in the project: stackblitz.com/edit/angular-ivy-kvbih4Leporine
O
2

Importing from handlebars/dist/amd/handlebars or handlebars/dist/cjs/handlebars works but the handlebars package has to be added to the allowedCommonJsDependencies.

Ottinger answered 15/9, 2021 at 13:5 Comment(4)
This answer does not work well, compilation failed on Could not find a declaration file for module 'handlebars/dist/amd/handlebars'. '/Users/......./node_modules/handlebars/dist/amd/handlebars.js' implicitly has an 'any' type. Try `npm i --save-dev @types/handlebars` if it exists or add a new declaration (.d.ts) file containing `declare module 'handlebars/dist/amd/handlebars'; . Is there please some another step?Plains
I got it to compile by adding a handlebars.d.ts file with these contents: declare module 'handlebars/dist/cjs/handlebars' { import * as Handlebars from 'handlebars'; export const precompile: typeof Handlebars.precompile; export const compile: typeof Handlebars.compile; }Nighthawk
@JoeSkeen Did you manage to make it work? for me, compiles but, I'm getting an error with node_modules, working on an Angular projectKriskrischer
Yes, let me look it up and I will share a gistNighthawk

© 2022 - 2024 — McMap. All rights reserved.