Install Node.js, NPM, and Gulp CLI in a new project along with SASS, Gulp-SASS, PostCSS, CSSNano, and Gulp-Terser. (BrowserSync is omitted.)
SCSS and JS Files:
Create an ‘app” directory in your project folder. Then within this new directory, create a ‘js’ directory and ‘scss’ directory with a ‘styles.scss’ and ‘scripts.js’ file in each respective directory. For testing purposes, add a couple lines of SASS and JS to each.
Command Line:
Open a new terminal and run the following to confirm that NodeJS and NPM are already installed.
node -v
npm -v
If both are installed, then proceed. Otherwise install NodeJS and NPM on your machine.
In the terminal, enter the following to install Gulp-CLI globally (-g) on your machine:
npm install gulp-cli -g
Once the global installation is complete then create a package.json file:
npm init -y
Install the necessary packages:
npm install gulp sass gulp-sass gulp-postcss cssnano gulp-terser
JavaScript:
Create your gulpfile.js configuration file in the project folder:
Thank you to Coder Coder for this configuration.
const { src, dest, watch, series } = require('gulp');
const sass = require('gulp-sass')(require('sass'));
const postcss = require('gulp-postcss');
const cssnano = require('cssnano');
const terser = require('gulp-terser');
// Sass Task
function scssTask(){
return src('app/scss/styles.scss', { sourcemaps: true })
.pipe(sass())
.pipe(postcss([cssnano()]))
.pipe(dest('dist', { sourcemaps: '.' }));
}
// JavaScript Task
function jsTask(){
return src('app/js/scripts.js', { sourcemaps: true })
.pipe(terser())
.pipe(dest('dist', { sourcemaps: '.' }));
}
// Watch Task
function watchTask(){
watch(['app/scss/**/*.scss', 'app/js/**/*.js'], series(scssTask, jsTask));
}
// Default Gulp task
exports.default = series(
scssTask,
jsTask,
watchTask
);
Command Line:
Open the PowerShell application in Windows and run the following in order to allow scripts to run via Visual Studio Code’s PowerShell terminal.
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser
Run Gulp in the command line to begin watching your files. Any changes will then be saved in the ‘dist’ directory.
gulp
Create .gitignore file
In order to keep your repository clean, create a .gitignore file and set it to ignore the ‘node_modules’ directory.
WordPress (Optional):
If this is a WordPress theme project then open functions.php and add or edit the following:
function theme_files() {
wp_enqueue_style('main-styles', get_theme_file_uri('/dist/styles.css'));
wp_enqueue_script('main-scripts', get_theme_file_uri('/dist/scripts.js'), NULL, '1.0', true);
}
add_action('wp_enqueue_scripts', 'theme_files');