How to use eleventy-load
1. Install eleventy-load #
We’ll assume that you already know how to create a site with Eleventy. To use eleventy-load in our Eleventy project, first we need to install it as a dependency.
npm install --save-dev eleventy-load
2. Add eleventy-load as a plugin #
After we have installed eleventy-load, we can add it as a plugin in our Eleventy configuration file.
module.exports = function (eleventyConfig) {
eleventyConfig.addPlugin(require("eleventy-load"));
};
Now you can run your Eleventy project, but we haven’t actually told eleventy-load to do anything yet…
Try giving me some rules!
3. Install loaders #
Loaders are the brains of eleventy-load; without them, nothing will happen. Say that we want to import Sass files like we would import CSS files, with a link
element.
<link rel="stylesheet" href="styles.scss" />
There are four things that loaders can do for us:
- Find the
link
element in the HTML template. - Load the Sass and convert it into CSS.
- Optionally, find dependencies (like background images) in the CSS.
- Save the CSS into a file.
Let’s install these loaders now.
npm install --save-dev eleventy-load-html eleventy-load-sass eleventy-load-css eleventy-load-file
4. Apply loaders with rules #
Loaders are applied to files using ‘rules’. A rule consists of a ‘test’ and a number of loaders. A test is a regular expression which is matched against filenames. For example, a rule which applied eleventy-load-html against every file ending in .md
or .html
would look like this:
{
test: /\.(md|html)$/,
loaders: [
{
loader: require("eleventy-load-html"),
},
],
},
Note that the test is matched against the input filename, not the output, hence we need to apply eleventy-load-html to Markdown files as well as HTML files.
We can set up rules so that eleventy-load imports Sass files using link
elements.
module.exports = function (eleventyConfig) {
eleventyConfig.addPlugin(require("eleventy-load"), {
rules: [
{
test: /\.(md|html)$/,
loaders: [
{
loader: require("eleventy-load-html"),
},
],
},
{
test: /\.scss$/,
loaders: [
{
loader: require("eleventy-load-sass"),
},
{
loader: require("eleventy-load-css"),
},
{
loader: require("eleventy-load-file"),
options: {
name: "[hash].css",
},
},
],
},
],
});
};
Optionally test the resource query #
Specify resourceQuery
to test the query parameters of the requested resource.
The following configuration will add inline styles for any resource loaded with inline
in the query parameter, for example, example.scss?inline
.
{
test: /\.scss$/,
resourceQuery: /inline/,
loaders: [
{
loader: require("eleventy-load-sass"),
},
{
loader: require("eleventy-load-css"),
},
{
loader: (content) => {
return `<style>${content}</style>`;
},
},
],
}
5. You’re ready to go #
That’s all it takes to set up eleventy-load to import Sass files using link
elements.