I have a sample.11ty.js
file, containing the following code:
module.exports = "<p>sample</p>";
In a njk
layout file, I tried to include the above sample.11ty.js
file like so:
{% include "components/sample.11ty.js" %}
The sample
paragraph does not display, but there is the following error in the console:
Reference Error: module is not defined
How can I include a
.11ty.js
file in anjk
template?
As mentioned in the official Nunjucks documentation:
an include is not a pre-processor that pulls the included template code into the including template before rendering; instead, it fires off a separate render of the included template, and the results of that render are included.
So it seems that trying to pre-process javascript in a Nunjucks include file is deemed to fail.
However, the following works:
In a njk
layout file, use the following frontmatter:
---
layout: layouts/sample.11ty.js
---
And in layouts/sample.11ty.js
, use a javascript class like so:
class Sample {
data() {
return {
name: "Eleventy"
};
}
render(data){
return data.content;
}
}
module.exports = Sample;