I'm new to Gulp
and trying to automate some tasks. Here's my environment setup: npm version: 8.1.0
, node version 17.0.1
, gulp CLI version 2.3.0
and gulp version 4.0.2
And here's my gulpfile.js
:
// list of dependencies ( things require to run the below funcitions)
const { src, dest, watch, series } = require('gulp');
const sass = require('gulp-sass');
const prefix = require('gulp-autoprefixer');
const minify = require('gulp-clean-css');
const terser = require('gulp-terser');
const imagemin = require('gulp-imagemin');
const imagewebp = require('gulp-webp');
// create functions
// SCSS
function compilescss() {
return src('src/scss/*.scss')
.pipe(sass())
.pipe(prefix('last 2 versions'))
.pipe(minify())
.pipe(dest('/dist/css'))
}
// JS
function jsmin(){
return src('src/js/*.js')
.pipe(terser())
.pipe(dest('dist/js'))
}
// images
function optimizeimg() {
return src('src/img/*.{jpg,png}')
.pipe(imagemin([
imagemin.mozjpeg({quality: 80, progressive: true}),
imagemin.optipng({optiminzationLevel: 2})
]))
.pipe(dest('dist/img'))
}
// webp images
function webpImage() {
return src('dist/img/*.{jpg, png}')
.pipe(imagewebp())
.pipe('dist/img')
}
// create watchlist
function watchTask(){
watch('src/scss/*.scss', compilescss);
watch('src/js/*.js', jsmin);
watch('src/img/*.{jpg,png}', optimizeimg);
watch('dist/img/*.{jpg,png}', webpImage);
}
// default gulp
exports.default = series(
compilescss,
jsmin,
optimizeimg,
webpImage,
watchTask
);
When I'm trying to run gulp
command in the terminal. I'm getting errors like - Error [ERR_REQUIRE_ESM]: require() of ES Module E:\Projects\portfolio\node_modules\gulp-imagemin\index.js from E:\Projects\portfolio\gulpfile.js not supported.
I've tried solutions like - adding type:"module"
in package.json and instead of require()
used import
but I couldn't make it work. So how can I fix this??? Thanks!
gulp-imagemin 8.0.0 and above are now ESM only. You can downgrade gulp-imagemin to 7.1.0 which is commonjs and it should work fine.
This package is now pure ESM. Please read this.
https://github.com/sindresorhus/gulp-imagemin/releases/tag/v8.0.0