How to use Sass in eleventy 2.0 using Gulp
Eleventy does not support Sass out of the box.
Luckily, there is an official document on how to add Sass support on their website.
And also many plugins for the job.
In this article, I will teach you how to use Sass in Eleventy 2.0 project using Gulp.
1. Install Gulp #
The first thing you need to do is install the gulp
package.
npm install gulp --save-dev
2. Install Sass-related packages #
Then we install tools that convert an SCSS to a CSS file.
gulp-sass
version 5 does not include a default Sass compiler, so you must install one (either node-sass or sass) along with gulp-sass
.
In this case, I choose sass
.
npm install sass gulp-sass --save-dev
3. Create a gulpfile.js in your project root directory #
A gulpfile.js
automatically load when you run the gulp command.
It is a place to create instructions for all gulp-related commands.
We set up two tasks here.
- A
styles
task which reads.scss
files insrc/styles/**/*.scss
and compiles them into.css
. And put them insrc/_includes/styles/
. - A
watch
task that monitorssrc/styles/**/*.scss
and executes thestyles
command when detecting the change.
var gulp = require('gulp');
const sass = require('gulp-sass')(require('sass'));
var paths = {
styles: {
src: 'src/styles/**/*.scss',
dest: 'src/_includes/styles/'
}
};
/*
* Define our tasks
*/
function styles() {
return gulp.src(paths.styles.src)
.pipe(sass())
.pipe(gulp.dest(paths.styles.dest));
}
function watch() {
gulp.watch(paths.styles.src, styles);
}
var build = gulp.series(styles);
exports.styles = styles;
exports.watch = watch;
exports.build = build;
/*
* Define default task that can be called by just running `gulp` from cli
*/
exports.default = build;
These tasks can be called from the terminal via gulp watch
, gulp styles
, or gulp
(gulp build
).
Run gulp when starting Eleventy #
We don't want to run those gulp commands manually every time we run an eleventy server.
You can automate this process by automatically running gulp
commands in a package.json
script.
"scripts": {
"build": "gulp build && npx @11ty/eleventy",
"start": "gulp build && gulp watch & npx @11ty/eleventy --serve"
},
Now, when we start an eleventy server with npm run start
, we will also run gulp
commands along.
Extra watch #
Eleventy does not automatically watch every file in our project's directory. E.g., it does not watch for the output folder and any changes to files and folders listed in your .gitignore
.
If the changes to your SCSS files are not reflected in the browser, you can fix them using either method based on your settings.
Add your own watch targets #
You can use the addWatchTarget
method to manually add a file or directory for Eleventy to watch.
eleventyConfig.addWatchTarget('your/custom/path')
Watch ignored files #
Eleventy will ignore changes to files or folders listed in your .gitignore
file by default.
To make it watch, you have to set setUseGitIgnore
to false
.
eleventyConfig.setUseGitIgnore(false);