Gulp imagemin ошибка

Установил gulp-imagemin командой npm i -D gulp-imagemin после подключил его в gulpfile.js const imagemin = require("gulp-imagemin");

При попытке запустить gulp получаю вот такую ошибку:

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: C:UsersTema05Desktopweb2021patternnode_modulesgulp-imageminindex.js
require() of ES modules is not supported.
require() of C:UsersTema05Desktopweb2021patternnode_modulesgulp-imageminindex.js from C:UsersTema05Desktopweb2021patterngulpfile.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from C:UsersTema05Desktopweb2021patternnode_modulesgulp-imageminpackage.json.
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1089:13)
    at Module.load (internal/modules/cjs/loader.js:937:32)
    at Function.Module._load (internal/modules/cjs/loader.js:778:12)
    at Module.require (internal/modules/cjs/loader.js:961:19)
    at require (internal/modules/cjs/helpers.js:92:18)
    at Object.<anonymous> (C:UsersTema05Desktopweb2021patterngulpfile.js:35:16)
    at Module._compile (internal/modules/cjs/loader.js:1072:14)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10)
    at Module.load (internal/modules/cjs/loader.js:937:32)
    at Function.Module._load (internal/modules/cjs/loader.js:778:12) {
  code: 'ERR_REQUIRE_ESM'
}

Из текста ошибки решил что нужно подключить через import import imagemin from "gulp-imagemin"; после чего ошибка изменилась

import imagemin from "gulp-imagemin";
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at wrapSafe (internal/modules/cjs/loader.js:988:16)
    at Module._compile (internal/modules/cjs/loader.js:1036:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10)
    at Module.load (internal/modules/cjs/loader.js:937:32)
    at Function.Module._load (internal/modules/cjs/loader.js:778:12)
    at Module.require (internal/modules/cjs/loader.js:961:19)
    at require (internal/modules/cjs/helpers.js:92:18)
    at requireOrImport (C:UsersTema05AppDataRoamingnpmnode_modulesgulp-clilibsharedrequire-or-import.js:19:11)
    at execute (C:UsersTema05AppDataRoamingnpmnode_modulesgulp-clilibversioned^4.0.0index.js:37:3)
    at Liftoff.handleArguments (C:UsersTema05AppDataRoamingnpmnode_modulesgulp-cliindex.js:211:24)

Погуглив нашёл другой вопрос https://stackoverflow.com/questions/58384179/syntaxerror-cannot-use-import-statement-outside-a-module и попытался использовать решение в виде добавления в файл package.json "type": "module" но это ломало подключение остальных пакетов. Все подключали gulp-imagemin через require, а также в первой ошибке сказано что нужно наоборот удалить "type": "module". Решил что иду не в том направлении и проблема в установке.

npm WARN deprecated uuid@3.4.0: Please upgrade  to version 7 or higher.  Older versions may use Math.random() in certain circumstances, which is known to be problematic.  See https://v8.dev/blog/math-random for details.
npm WARN pattern@1.0.0 No repository field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@2.3.2 (node_modulesbrowser-syncnode_modulesfsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@2.3.2: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.13 (node_modulesfsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.13: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@2.3.2 (node_modulessassnode_modulesfsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@2.3.2: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

+ gulp-imagemin@8.0.0
updated 1 package and audited 836 packages in 8.795s

27 packages are looking for funding
  run `npm fund` for details

found 6 vulnerabilities (1 low, 2 moderate, 3 high)
  run `npm audit fix` to fix them, or `npm audit` for details

Сначала установил uuid версии 7.0.3 при помощи команды npm i uuid. Далее посмотрел детали 3 уязвимостей статута «high» которые появились после установки gulp-imagemin.

High            Regular Expression Denial of Service                          

  Package         trim-newlines                                                 

  Patched in      >=3.0.1 <4.0.0 || >=4.0.1                                     

  Dependency of   gulp-imagemin [dev]                                           

  Path            gulp-imagemin > imagemin-gifsicle > gifsicle > logalot >      
                  squeak > lpad-align > meow > trim-newlines                    

  More info       https://npmjs.com/advisories/1753                             


  Package         trim-newlines                                                 

  Patched in      >=3.0.1 <4.0.0 || >=4.0.1                                     

  Dependency of   gulp-imagemin [dev]                                           

  Path            gulp-imagemin > imagemin-mozjpeg > mozjpeg > logalot >        
                  squeak > lpad-align > meow > trim-newlines                    

  More info       https://npmjs.com/advisories/1753                             


  High            Regular Expression Denial of Service                          

  Package         trim-newlines                                                 
  Patched in      >=3.0.1 <4.0.0 || >=4.0.1                                     

  Dependency of   gulp-imagemin [dev]                                           

  Path            gulp-imagemin > imagemin-optipng > optipng-bin > logalot >    
                  squeak > lpad-align > meow > trim-newlines                    

  More info       https://npmjs.com/advisories/1753                    

Перешёл по ссылке https://npmjs.com/advisories/1753 где было сказано что нужно установить trim-newlines нужной версии. Я установил trim-newlines версии 4.0.2 командой npm install trim-newlines

После переустановки gulp-imagemin нечего не изменилось. Просьба обновить uuid и 3 уязвимости остались. Чистка кеша с атрибутом —force, переустановка и полное удаление node.js по инструкции в вопросе https://stackoverflow.com/questions/20711240/how-to-completely-remove-node-js-from-windows нечего не изменили.

Поиск решения приводил к ошибкам установки или ошибкам непосредственной работы пакета. Никаких похожих проблем именно с подключением не нашёл.

Содержимое gulpfile.js

const src_folder = "src";
const dist_folder = "dist";
const path = {
    src: {
        html: [src_folder + "/*.html", "!" + src_folder + "/_*.html"],
        scss: [src_folder + "/scss/*.scss", "!" + src_folder + "/scss/_*.scss"],
        js: [src_folder + "/js/*.js", "!" + src_folder + "/js/_*.js"],
        img: src_folder + "/img/**/*.{jpg,png,svg,gif,ico,webp}",
        fonts: src_folder + "fonts/*.ttf"
    },
    dist: {
        html: dist_folder,
        css: dist_folder + "/css",
        js: dist_folder + "/js",
        img: dist_folder + "/img",
        fonts: dist_folder + "/fonts"
    },
    watch: {
        html: src_folder + "/*.html",
        scss: src_folder + "/scss/*.scss",
        js: src_folder + "/js/*.js"
    },
    clean: dist_folder
}

const del = require("del");
const { src, dest, watch, series } = require("gulp");
const fileinclude = require("gulp-file-include");
const sass = require("gulp-sass")(require("sass"));
const groupcssmediaqueries = require("gulp-group-css-media-queries");
const autoprefixer = require("gulp-autoprefixer");
const cleancss = require("gulp-clean-css");
const uglifyes = require("gulp-uglify-es").default;
const rename = require("gulp-rename");
// const imagemin = require("gulp-imagemin"); <------------------------------------------------------------
const browsersync = require("browser-sync").create();

function cleanFiles() {
    return del(dist_folder);
};

function parseHtml(done) {
    src(path.src.html)
        .pipe(fileinclude())
        .pipe(dest(path.dist.html));
    done();
};

function parseScss(done) {
    src(path.src.scss)
        .pipe(sass())
        .pipe(groupcssmediaqueries())
        .pipe(autoprefixer({
            overrideBrowserslist: ["last 5 versions"]
        }))
        .pipe(dest(path.dist.css))
        .pipe(cleancss())
        .pipe(rename({
            suffix: ".min"
        }))
        .pipe(dest(path.dist.css));
    done();
};

function parseJs(done) {
    src(path.src.js)
        .pipe(dest(path.dist.js))
        .pipe(uglifyes())
        .pipe(rename({
            suffix: ".min"
        }))
        .pipe(dest(path.dist.js));
    done();
};

function parseImg(done) {
    src(path.src.img)
        //.pipe(imagemin())
        .pipe(dest(path.dist.img));
    done();
};

function browserInit(done) {
    browsersync.init({
        server: dist_folder,
        notify: false
    });
    done();
};

function browserReload(done) {
    browsersync.reload();
    done();
}

function watchFiles(done) {
    watch(path.watch.html, series(parseHtml, browserReload));
    watch(path.watch.scss, series(parseScss, browserReload));
    watch(path.watch.js, series(parseJs, browserReload));
    done();
};

exports.default = series(cleanFiles, parseHtml, parseScss, parseJs, parseImg, browserInit, watchFiles);

Содержимое package.json

{
  "name": "pattern",
  "version": "1.0.0",
  "description": "gulp",
  "main": "gulpfile.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "author": "fls",
  "license": "ISC",
  "devDependencies": {
    "browser-sync": "^2.27.5",
    "del": "^6.0.0",
    "gulp": "^4.0.2",
    "gulp-autoprefixer": "^8.0.0",
    "gulp-clean-css": "^4.3.0",
    "gulp-file-include": "^2.3.0",
    "gulp-group-css-media-queries": "^1.2.2",
    "gulp-imagemin": "^8.0.0",
    "gulp-rename": "^2.0.0",
    "gulp-sass": "^5.0.0",
    "gulp-uglify-es": "^3.0.0",
    "sass": "^1.38.0"
  },
  "dependencies": {
    "trim-newlines": "^4.0.2",
    "uuid": "^7.0.3"
  }
}

Пробую установить gulp-imagemin, но при запуске команды gulp-imagemin в терминале выдает ошибку:
ReferenceError: require is not defined in ES module scope, you can use import instead
This file is being treated as an ES module because it has a ‘.js’ file extension and ‘C:UserstempeDesktopgulp-startpackage.json’ contains «type»: «module». To treat it as a CommonJS script, rename it to use the
‘.cjs’ file extension
. Я так и не понял какой файл надо переименовать с расширением cjs. Помогите разобраться, как сделать импорт изображений из одной папки, сжать изображение и перенести их в другую папку. Пробовал через импорт, как написано в документации, но не получилось.

Для полноты картины вот архив с файлами https://drive.google.com/file/d/1WOsc51FwDwQTsfMs1…

Вот что у меня написано в gulpfile.js

const { src, dest, watch, parallel } = require('gulp');
const scss = require('gulp-sass')(require('sass'));
const concat = require('gulp-concat');
const browserSync = require('browser-sync').create();
const uglify = require('gulp-uglify-es').default;
const autoprefixer = require('gulp-autoprefixer');
const imagemin = require('gulp-imagemin');



function browsersync() {
    browserSync.init({
        server: {
            baseDir: "app/"
        }
    });
}


function images() {
    return src('app/images/**/*')
        .pipe(imagemin(
            [
                imagemin.gifsicle({ interlaced: true }),
                imagemin.mozjpeg({ quality: 75, progressive: true }),
                imagemin.optipng({ optimizationLevel: 5 }),
                imagemin.svgo({
                    plugins: [
                        { removeViewBox: true },
                        { cleanupIDs: false }
                    ]
                })
            ]
        ))
        .pipe(dest('dist/images'))
}

function scripts() {
    return src([
        'node_modules/jquery/dist/jquery.js',
        'app/js/main.js'
    ])
        .pipe(concat('main.min.js'))
        .pipe(uglify())
        .pipe(dest('app/js'))
        .pipe(browserSync.stream());

}


function styles() {
    return src('app/scss/style.scss')
        .pipe(scss({ outputStyle: 'expanded' }))
        .pipe(concat('style.min.css'))
        .pipe(autoprefixer({
            overrideBrowserslist: ['last 10 version'],
            grid: true
        }))
        .pipe(dest('app/css'))
        .pipe(browserSync.stream());
}

function build() {
    return src([
        'app/css/style.min.css',
        'app/fonts/**/*',
        'app/js/main.min.js ',
        'app/*.html'
    ], { base: 'app' })
        .pipe(dest('dist'))
}

function watching() {
    watch(['app/scss/**/*.scss'], styles);
    watch(['app/js/**/*.js', '!app/js/main.min.js'], scripts);
    watch(["app/*.html"]).on('change', browserSync.reload);

}

exports.styles = styles;
exports.watching = watching;
exports.browsersync = browsersync;
exports.scripts = scripts;
exports.build = build;
exports.images = images;




exports.default = parallel(scripts, watching, browsersync);

package.json

{
  "name": "gulp-start",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "author": "Igor Ilin",
  "license": "ISC",
  "devDependencies": {
    "@babel/cli": "^7.15.4",
    "@babel/core": "^7.15.5",
    "@babel/node": "^7.15.4",
    "@babel/preset-env": "^7.15.6",
    "browser-sync": "^2.27.5",
    "gulp": "^4.0.2",
    "gulp-autoprefixer": "^8.0.0",
    "gulp-concat": "^2.6.1",
    "gulp-imagemin": "^8.0.0",
    "gulp-sass": "^5.0.0",
    "gulp-sourcemaps": "^3.0.0",
    "gulp-uglify-es": "^3.0.0",
    "gulp-watch": "^5.0.1",
    "jquery": "^3.6.0",
    "sass": "^1.39.2"
  },
  "dependencies": {
    "autoprefixer": "^10.3.4",
    "express": "^4.16.4",
    "gulp-uglify": "^3.0.2",
    "imagemin-gifsicle": "^7.0.0",
    "imagemin-mozjpeg": "^9.0.0",
    "module": "^1.2.5"
  }
}

Hi,

I am running a Windows 10 OS and trying to use gulp4 with imagemin to minify some png files. But ran into errors:

Here is my gulpfile:

var gulp = require('gulp4'),
    concat = require('gulp-concat'),
    uglify = require('gulp-uglify'),
    myth = require('gulp-myth'),
    jshint = require('gulp-jshint'),
    imagemin = require('gulp-imagemin');

var paths = {
    js: 'app/js/*.js',
    css: 'app/css/*.css',
    images: 'app/img/*.{JPG,jpg,png,gif}',
};

//Styles Task
gulp.task('styles', function(){
    return gulp.src(paths.css)
               .pipe(concat('all.css'))
               .pipe(myth())
               .pipe(gulp.dest('dist'));
});

//Scripts Task
gulp.task('scripts', function() {
    return gulp.src(paths.js)
               .pipe(jshint())
               .pipe(jshint.reporter('default'))
               .pipe(concat('all.js'))
               .pipe(uglify())
               .pipe(gulp.dest('dist'));
});

//Images Task
gulp.task('images', function(){
    return gulp.src(paths.images)
               .pipe(imagemin())
               .pipe(gulp.dest('dist/img'));
});

//Watch Task
gulp.task('watch', function() {
    gulp.watch(paths.css,gulp.series('styles'));
    gulp.watch(paths.js, gulp.series('scripts'));
    gulp.watch(paths.images,gulp.series('images'));
});

//Default task
gulp.task('default', 
gulp.parallel('styles','scripts','images','watch'));

Here is the error:

[10:57:44] Using gulpfile D:DocumentsWorkingGulpgulp-bookgulpfile.js
[10:57:44] Starting 'default'...
[10:57:44] Starting 'styles'...
[10:57:44] Starting 'scripts'...
[10:57:44] Starting 'images'...
[10:57:44] Starting 'watch'...
[10:57:45] Finished 'styles' after 874 ms
[10:57:45] Finished 'scripts' after 881 ms
[10:57:45] 'images' errored after 913 ms
[10:57:45] Error in plugin "gulp-imagemin"
Message:
    The system cannot find the path specified.

Details:
    errno: ENOENT
    code: ENOENT
    syscall: spawn D:DocumentsWorkingGulpgulp-booknode_modulesoptipng-binvendoroptipng.exe
    killed: false
    stdout:
    stderr: The system cannot find the path specified.

    failed: true
    signal: null
    cmd: D:DocumentsWorkingGulpgulp-booknode_modulesoptipng-binvendoroptipng.exe -strip all -clobber -fix -o 3 -out C:UsersabhilkAppDataLocalTemp4f2800d8-3bc0-47e1-95a0-2c9e73133c05 C:UsersabhilkAppDataLocalTempbf26e857-0623-4783-b68a-c76223792cd3
    timedOut: false
    fileName: D:DocumentsWorkingGulpgulp-bookappimggulp.png
    domainEmitter: [object Object]
    domain: [object Object]
    domainThrown: false

[10:57:45] 'default' errored after 954 ms
[10:57:45] The following tasks did not complete: watch
[10:57:45] Did you forget to signal async completion?
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! gulp-book@1.0.0 taskrunner: `gulp4`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the gulp-book@1.0.0 taskrunner script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:UsersabhilkAppDataRoamingnpm-cache_logs2018-02-06T05_27_45_442Z-debug.log

package.json file:

  "name": "gulp-book",
  "version": "1.0.0",
  "description": "",
  "main": "gulpfile.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1",
    "taskrunner": "gulp4"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "gulp": "^3.9.1",
    "gulp-concat": "^2.6.1",
    "gulp-imagemin": "^4.1.0",
    "gulp-jshint": "^2.1.0",
    "gulp-myth": "^1.1.0",
    "gulp-uglify": "^3.0.0",
    "gulp4": "^4.0.2",
    "imagemin-jpegtran": "^5.0.2",
    "imagemin-pngquant": "^5.0.1",
    "jshint": "^2.9.5",
    "pngquant-bin": "^3.1.1"
  },
  "dependencies": {
    "optipng-bin": "^4.0.0"
  }
}

Please let me how I can resolve this. Thanks :)

I want to compress the images and pipe to the directory of dist,but the dist is empty after run the task.
this is my task

gulp.task("minify_img", function() {
  gulp.src("src/img/*")
    .pipe(imagemin())
    .pipe(gulp.dest("/dist/img"));
});

Nhan's user avatar

Nhan

3,5986 gold badges29 silver badges38 bronze badges

asked Nov 17, 2016 at 3:24

zhaohe's user avatar

Try this:

return gulp.src("src/img/*");

Malekai's user avatar

Malekai

4,7135 gold badges25 silver badges59 bronze badges

answered Dec 22, 2020 at 16:06

huss's user avatar

1

With your current destination path /dist/img, the files will be at the root of your drive (e.g. D:/dist/img). You should add a dot before it, then the files will be exported to the root of your project.

.pipe(gulp.dest("./dist/img"));

answered Nov 17, 2016 at 3:58

Nhan's user avatar

NhanNhan

3,5986 gold badges29 silver badges38 bronze badges

4

gulp – Error [ERR_REQUIRE_ESM]: require not supported” is a common error related to the ESM only package in NodeJS. The below explanations can help you know more about this error of causes and solutions.

When working with gulp in JavaScript, you may sometimes encounter this error. This error happens due to the many following reasons:

First, it might be because gulp-image package is no longer a CommonJS module, but an ES module, which using require() to import will cause the error:

var gulp = require("gulp");
var image = require("gulp-image");

Output: 

Error [ERR_REQUIRE_ESM]: require() of ES Module B:node_modulesgulp-imageindex.js from B:index.js not supported.

Second, it might be because the package gulp-imagemin v8.0.0 permanently moved to the pure ESM (without dual support), which required you to change the gulpfile to ESM so as to continue using it. The current gulp-imagemin version is only compatible with an ESM import.

To see how to solve this problem, please read the following instructions.

How to solve the error?

Install the old gulp-imagemin instead

To solve the gulp – Error [ERR_REQUIRE_ESM]: require not supported, you will have to open the terminal in your project’s root and run this command:

npm install --save [email protected]

Or if you are using TypeScript, you must use this command instead:

npm install --save @types/[email protected]

Then you can run again to see if the error has been solved.

node index.js

You should get the following outputs: 

This method is very simple because the newest version of the package gulp-imagemin only exports an ES module, therefore if you want to use the command require(“gulp-imagemin”) to import it, you must use the older version of it such as 7.1.0 because these versions support the require() of CommonJS module. If you still want to use the up-to-date versions and feel free to change your import command, then the next solution is for you.

Use a dynamic import() instead of require()

The import() syntax, also known as dynamic import, is a function-like expression that allows loading an ES module asynchronously and dynamically into a potentially non-module environment. Therefore, you can use the dynamic import() to use an ES module such as gulp-imagemin or gulp-image instead of using require() as it only supports CommonJS modules. For example:

var gulp = require("gulp");
import image from 'gulp-image'
import imagemin from 'gulp-imagemin'

This approach may be easy for some small projects, but we don’t suggest using newer versions on larger projects because it will require a complete re-architecture. To install the updated version of these packages, just run this command in your terminal:

Summary

We have learned how to deal with the “gulp – Error [ERR_REQUIRE_ESM]: require not supported” in JavaScript and NodeJS. By applying the first solution to your project, you can quickly solve it. If you are working with JavaScript or NodeJS, you can visit our websites to read more articles about it.

Maybe you are interested:

  • [ERR_REQUIRE_ESM]: require() not supported
  • Bootstrap dropdown require Popper.js Error in JavaScript

I’m Edward Anderson. My current job is as a programmer. I’m majoring in information technology and 5 years of programming expertise. Python, C, C++, Javascript, Java, HTML, CSS, and R are my strong suits. Let me know if you have any questions about these programming languages.


Name of the university: HCMUT
Major: CS
Programming Languages: Python, C, C++, Javascript, Java, HTML, CSS, R

Issue

First time I am using gulp.In my gulpfile.js contains

var gulp = require('gulp');
var imagemin = require('gulp-imagemin');
gulp.task('default', function () { console.log('Hello Gulp!') });
gulp.task('imagemin', function() {
   var img_src = 'src/images/**/*', img_dest = 'build/images';

   gulp.src(img_src)
   .pipe(changed(img_dest))
   .pipe(imagemin())
   .pipe(gulp.dest(img_dest));
});

When running Git bash from my woking folder as
$ gulp imagemin

But it shows the following error

[11:35:12] Using gulpfile C:xampphtdocsworkgulpfile.js
[11:35:12] Starting 'imagemin'...
[11:35:12] 'imagemin' errored after 10 ms
[11:35:12] ReferenceError: changed is not defined
    at Gulp.<anonymous> (C:xampphtdocsworkgulpfile.js:8:10)
    at module.exports (C:xampphtdocsworknode_modulesorchestratorlibrunTask.js:34:7)
    at Gulp.Orchestrator._runTask (C:xampphtdocsworknode_modulesorchestratorindex.js:273:3)
    at Gulp.Orchestrator._runStep (C:xampphtdocsworknode_modulesorchestratorindex.js:214:10)
    at Gulp.Orchestrator.start (C:xampphtdocsworknode_modulesorchestratorindex.js:134:8)
    at C:Users58_userAppDataRoamingnpmnode_modulesgulpbingulp.js:129:20
    at _combinedTickCallback (internal/process/next_tick.js:67:7)
    at process._tickCallback (internal/process/next_tick.js:98:9)
    at Module.runMain (module.js:607:11)
    at run (bootstrap_node.js:418:7)

How can I rectify this issue? Please help me. Can anybody provide gulp installation guidlines for angularjs. Thanks in advance

Solution

var gulp = require('gulp');
var imagemin = require('gulp-imagemin');
gulp.task('default', function () { console.log('Hello Gulp!') });
gulp.task('imagemin', function() {
   var img_src = 'src/images/**/*', img_dest = 'build/images';

   gulp.src(img_src)
   .pipe(imagemin())
   .pipe(gulp.dest(img_dest));
});

remove unnecessary undefined task changed. .pipe(changed(img_dest)).

Answered By – Nikhil Mohanan

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

У меня те же проблемы, и я обнаружил, что плагины по умолчанию не были установлены правильно.

npm install imagemin-jpegtran imagemin-svgo imagemin-gifsicle imagemin-optipng --save

Это предупреждение было выдано этими строками кода # L12

const loadPlugin = (plugin, args) => {
  try {
    return require(`imagemin-${plugin}`).apply(null, args);
  } catch (err) {
    gutil.log(`gulp-imagemin: Couldn't load default plugin "${plugin}"`);
  }
};

Если ошибка журнала в catch, мы можем увидеть Module not found xxx,

try {
  return require(`imagemin-${plugin}`).apply(null, args);
} catch (err) {
  console.log(err); // and will throw error: XX Module Not Found
  gutil.log(`gulp-imagemin: Couldn't load default plugin "${plugin}"`);
}

Таким образом, мы могли бы установить потерянные пакеты.

Если также есть какая-то ошибка, просто переустановите imagemin

npm uninstall gulp-imagemin --save
npm install gulp-imagemin --save

Понравилась статья? Поделить с друзьями:
  • Haier hw60 12829a ошибка е1
  • Haier hw60 1282 коды ошибок
  • Haier hw60 1211n ошибка err2
  • Haier hw50 12866me ошибка err2
  • Haier hw fs1050txveme ошибка err7