require() of ES Module gulpfile.js not supported n gulp node js

4.6k Views Asked by At

gulpfile.js

'use strict';
const gulp = require("gulp");
const imagemin = require("gulp-imagemin");
const webp = require("imagemin-webp");
const extReplace = require("gulp-ext-replace");

gulp.task("exportWebP", function() {
  let src = "artists/**/*.jpg"; // Where your PNGs are coming from.
  let dest = "dist/images"; // Where your WebPs are going.

  return gulp.src(src)
    .pipe(imagemin([
      webp({
        quality: 75
      })
    ]))
    .pipe(extReplace(".webp"))
    .pipe(gulp.dest(dest));
});

package.json

{
  "type": "module",
  "main": "gulpfile.js",
  "dependencies": {
    "gulp-ext-replace": "^0.3.0",
    "gulp-imagemin": "^8.0.0",
    "imagemin-webp": "^7.0.0"
  },
  "devDependencies": {
    "gulp": "^4.0.2"
  }
}

here i run gulp js file it show the error

Error [ERR_REQUIRE_ESM]: require() of ES Module index.js from gulpfile.js not supported. Instead change the require of index.js in gulpfile.js to a dynamic import() which is available in all CommonJS modules. at Object. (gulpfile.js:3:18) at async Promise.all (index 0) { code: 'ERR_REQUIRE_ESM' } how to solve this problem.

2

There are 2 best solutions below

0
Konrad On

Many packages moved to esm modules and can no longer be imported using require

Change require to import

import gulp from "gulp";
import imagemin from "gulp-imagemin";
import webp from "imagemin-webp";
import extReplace from "gulp-ext-replace";
0
GABY KARAM On

You can dynamically import the imagmin package inside the function where you are using it.

for example let say before version 8, the function would look something like below:

function buildSprite() {
    return src(location.sprites.source + '*.svg')
        .pipe(imagemin.default([
            imagemin.svgo({
                plugins: [
                    {
                        removeViewBox: false,
                        collapseGroups: false
                    }
                ]
            })
        ]))
        .pipe(dest(location.sprites.dist));
}

after version 8 your function gonna look like below:

async function buildSprite() {
    const imagemin = await import('gulp-imagemin');
    return src(location.sprites.source + '*.svg')
        .pipe(imagemin.default([
            imagemin.svgo({
                plugins: [
                    {
                        removeViewBox: false,
                        collapseGroups: false
                    }
                ]
            })
        ]));
}