mde / ejs

Embedded JavaScript templates -- http://ejs.co
Apache License 2.0
7.77k stars 842 forks source link

Can't override fileLoader #398

Open brikis98 opened 6 years ago

brikis98 commented 6 years ago

I'm trying to use EJS with TypeScript as follows:

import * as ejs from "ejs";

ejs.fileLoader = (filePath: string): string => {
  throw new Error(`File loading not allowed. Tried to load: ${filePath}.`);
};

export function render(template: string, inputs: any): string {
  const compiledTemplate = ejs.compile(template);
  return compiledTemplate(inputs);
}

// Elsewhere:

render("include('foo')", {});

I ran the code above, and it succeeded, with the include of foo working just fine. This indicates that overriding ejs.fileLoader had no effect. I tried import ejs = require("ejs"), but that also didn't help.

Any suggestions on what I might be doing wrong?

brikis98 commented 6 years ago

Update: when I use the TypeScript bindings for EJS, I even get an error that fileLoader is readonly and cannot be overwritten! If I use import ejs = require("ejs"), that error goes away, but include still works...

brikis98 commented 5 years ago

It turns out the cause of this is that in ES6 and TypeScript, all imports are considered constant. So, to work with ES6/TypeScript, EJS will need to expose a new way to override the file loader.

brikis98 commented 5 years ago

Workaround: override the include keyword:

const fileLoader = (filePath: string): string => {
  throw new Error(`File loading not supported. Tried to load: ${filePath}.`);
};

const compiledTemplate = ejs.compile(`Hello, <%- include("foo") %>`);

// Will throw "File loading not supported" error
compiledTemplate({include: fileLoader});