Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support ES Modules in precompiled templates #2051

Open
arturober opened this issue Oct 6, 2024 · 1 comment
Open

Support ES Modules in precompiled templates #2051

arturober opened this issue Oct 6, 2024 · 1 comment
Labels
Milestone

Comments

@arturober
Copy link

This should not be too complicated because it doens't require much change from CommonJS. As an example, I've created a simple script that makes precompiled templates work with import. I'm running a client app (vanilla JavaScript with Vite).

I'm compiling my templates with CommonJS, and after that I run the script (package.json):

  "scripts": {
    "handlebars": "handlebars -c \"handlebars\" templates/*.hbs -f compiled.js --esm handlebars",
    "posthandlebars": "node hbs-replace.js",
    "prestart": "npm run handlebars",
    "start": "vite",
    "build": "vite build",
    "preview": "vite preview"
  }

This is the script hbs-replace.js:

import {replaceInFileSync} from 'replace-in-file';

const options = {
    files: './compiled.js',
    from: ['var Handlebars = require("handlebars");', /$/],
    to: ['import Handlebars from "handlebars/runtime";', 'export default templates;'],
}

replaceInFileSync(options);

The result (compiled.js):

import Handlebars from "handlebars/runtime"; // Replaced the required statement 
// Unmodified content
export default templates; // Added at the end

And this is how it can be used from code (import):

import templates from './compiled.js';
console.log(templates['example.hbs']({text: 'patata'}));
console.log(templates['example2.hbs']({text: 'patata'}));

Maybe this is not the most elegant way of exporting templates, but it's usable

@jaylinski
Copy link
Member

Related to #1816.

@jaylinski jaylinski added this to the 5.0.0 milestone Oct 6, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants