Importing Mustache template files directly into a ...
# workers-help
v
Hi everyone! I'm just starting to muck around a bit with Workers and itty-router and Mustache, ultimately what I'm trying to do is to have my Mustache templates as individual files straight in my repository (so I can get nice syntax highlighting in my IDE) and do essentially something like
import * as template from './templates/template.mustache
for use with the Mustache library itself. I've come across the workaround of loading the templates from R2 or KV, but I'd like to avoid that if at all possible. Really all I need is just to get them in as a string, I've seen things like this https://stackoverflow.com/questions/46503615/import-html-from-typescript-with-webpack but they're all based on mucking around with Webpack configuration. Given I'm new to all this ideally I'd like to be able to have it working locally with Wrangler2 as well. My understanding is that Wrangler2 uses
esbuild
under the covers, is there some customisation I can do with that to make this happen? 🙂 Or something other method that would allow this to work? Any thoughts or insights are greatly appreciated. ❤️
s
I think is what you're looking for
v
👀
I'll be damned, that worked PERFECTLY.
Thanks so much!! 😄
I should note for any future readers that to keep TypeScript happy I had to add a definition file:
Copy code
declare module '*.mustache' {
    const content: string;
    export default content;
}
And tell TypeScript about it at the top of the file I'm importing into:
Copy code
/// <reference path="mustache.d.ts"/>
s
You should also be able to add that to your tsconfig to avoid needing to reference it like that
v
Oooo, I will look into that.
Thanks so much again!!
Hmmmm, would you happen to know off the top of your head which specific option in
tsconfig.json
I'd be setting for that? I haven't been able to figure it out thus far. 😦
s
Did some googling, looks like it should just take your d.ts file without needing a reference actually 🤔
v
Hrmmmmm! Clearly I'm doing something wrong then, haha.
Might be time to post on Stack Overflow, I reckon.
OOOooooh!
Got it! The
.d.ts
file has to be named the same as the module I'm declaring (i.e. I changed it to
mustache.d.ts
and everything works). 🎉
s
Ah, great
2 Views