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

Add a precompile step #743

Open
terrablue opened this issue Sep 3, 2023 · 3 comments
Open

Add a precompile step #743

terrablue opened this issue Sep 3, 2023 · 3 comments

Comments

@terrablue
Copy link

Hi, is it possible to add a precompilation step like handlebars'? Such that it's possible to compile .ejs files once to JS, and then render them with different data.

As far as I can see, that would be pretty similar to ejs.compile, except that instead of constructing a function to be executed on the fly, the source code would be returned so that it can be saved to disk.

I don't mind submitting a PR if the idea is generally favored.

@morandd
Copy link

morandd commented Jun 7, 2024

This is possible in Eta, by calling .toString() on the result of .compile(). This technique may work in EJS too?
ref: eta-dev/eta#268

@terrablue
Copy link
Author

@morandd Hi, this is possible for Eta (see eta-dev/eta#268 (comment)), but EJS here produces the following code:

function anonymous(data) {
      var include = function (path, includeData) {
        var d = utils.shallowCopy(utils.createNullProtoObjWherePossible(), data);
        if (includeData) {
          d = utils.shallowCopy(d, includeData);
        }
        return includeFile(path, opts)(d);
      };
      return fn.apply(opts.context,
        [data || utils.createNullProtoObjWherePossible(), escapeFn, include, rethrow]);
    }

This does not seem to me as something you can easily import and call, without at least knowing what utils is and where it can be imported from. Also, it doesn't look to me as though the compiled template is included (unlike with Eta).

@morandd
Copy link

morandd commented Jun 7, 2024

you can easily import and call

What I did in Eta was

... .toString().replace("function anonymous(","function myFunction(")

then save that to a file myFunction.js then later I can import {myFunction} from './myFunction.js'.

Regarding the EJS utils object, if it's in scope as part of the closure when you execute myFunction() it should work.

I haven't done this in EJS so I'll stop talking now. (I just happened to see this thread while looking at another EJS Issue.) Good luck!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants