diff --git a/src/Engines/JavaScript.js b/src/Engines/JavaScript.js index 77eede3bd..95777d382 100644 --- a/src/Engines/JavaScript.js +++ b/src/Engines/JavaScript.js @@ -80,8 +80,15 @@ class JavaScript extends TemplateEngine { } async #getInstanceFromInputPath(inputPath) { - let isEsm = this.eleventyConfig.getIsProjectUsingEsm(); - const mod = await EleventyImport(inputPath, isEsm ? "esm" : "cjs"); + let mod; + let relativeInputPath = + this.eleventyConfig.directories.getInputPathRelativeToInputDirectory(inputPath); + if (this.eleventyConfig.userConfig.isVirtualTemplate(relativeInputPath)) { + mod = this.eleventyConfig.userConfig.virtualTemplates[relativeInputPath].content; + } else { + let isEsm = this.eleventyConfig.getIsProjectUsingEsm(); + mod = await EleventyImport(inputPath, isEsm ? "esm" : "cjs"); + } let inst = this._getInstance(mod); if (inst) { diff --git a/src/UserConfig.js b/src/UserConfig.js index c99927436..ac5eed57d 100644 --- a/src/UserConfig.js +++ b/src/UserConfig.js @@ -903,6 +903,10 @@ class UserConfig { }; } + isVirtualTemplate(virtualInputPath) { + return Boolean(this.virtualTemplates[virtualInputPath]); + } + #setDirectory(key, dir) { if (this.isPluginExecution()) { throw new Error( diff --git a/test/EleventyVirtualTemplatesTest.js b/test/EleventyVirtualTemplatesTest.js index 76a3f042f..2a0b73911 100644 --- a/test/EleventyVirtualTemplatesTest.js +++ b/test/EleventyVirtualTemplatesTest.js @@ -177,3 +177,46 @@ test("Virtual templates as layouts, issue #2307", async (t) => { t.deepEqual(results[0].content.trim(), `

Hello

`); t.deepEqual(results[0].rawInput, `# Hello`); }); + +test("11ty.js Virtual Templates (object), issue #3347", async (t) => { + let templateDefinition = { + data: () => { + return { var: 2 }; + }, + render: function(data) { + return `this is a test ${data.var}.`; + } + }; + + let elev = new Eleventy("./test/stubs-virtual-nowrite", "./test/stubs-virtual-nowrite/_site", { + config: function (eleventyConfig) { + eleventyConfig.addTemplate("virtual.11ty.js", templateDefinition); + } + }); + + let results = await elev.toJSON(); + + t.deepEqual(results.length, 1); + t.deepEqual(results[0].content.trim(), `this is a test 2.`); + // TODO support rawInput on 11ty.js? + // t.deepEqual(results[0].rawInput, templateDefinition); +}); + +test("11ty.js Virtual Templates (function), issue #3347", async (t) => { + let templateDefinition = function(data) { + return `this is a test ${data.page.url}.`; + }; + + let elev = new Eleventy("./test/stubs-virtual-nowrite", "./test/stubs-virtual-nowrite/_site", { + config: function (eleventyConfig) { + eleventyConfig.addTemplate("virtual.11ty.js", templateDefinition); + } + }); + + let results = await elev.toJSON(); + + t.deepEqual(results.length, 1); + t.deepEqual(results[0].content.trim(), `this is a test /virtual/.`); + // TODO support rawInput on 11ty.js? + // t.deepEqual(results[0].rawInput, templateDefinition); +});