Ошибка подключения пакета 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:\Users\Tema05\Desktop\web\2021\pattern\node_modules\gulp-imagemin\index.js
require() of ES modules is not supported.
require() of C:\Users\Tema05\Desktop\web\2021\pattern\node_modules\gulp-imagemin\index.js from C:\Users\Tema05\Desktop\web\2021\pattern\gulpfile.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:\Users\Tema05\Desktop\web\2021\pattern\node_modules\gulp-imagemin\package.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:\Users\Tema05\Desktop\web\2021\pattern\gulpfile.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:\Users\Tema05\AppData\Roaming\npm\node_modules\gulp-cli\lib\shared\require-or-import.js:19:11)
at execute (C:\Users\Tema05\AppData\Roaming\npm\node_modules\gulp-cli\lib\versioned\^4.0.0\index.js:37:3)
at Liftoff.handleArguments (C:\Users\Tema05\AppData\Roaming\npm\node_modules\gulp-cli\index.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 [email protected]: 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 [email protected] No repository field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\browser-sync\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\sass\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
+ [email protected]
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"
}
}
Ответы (4 шт):
gulpfile.js
const gulp = require("gulp"),
concat = require('gulp-concat'),
clean = require('gulp-clean'),
browserSync = require('browser-sync').create(),
imagemin = require('gulp-imagemin'),
sass = require('gulp-sass');
sass.compiler = require('node-sass');
uglify = require('gulp-uglify'),
pipeline = require('readable-stream').pipeline,
minifyjs = require('gulp-js-minify'),
cleanCSS = require('gulp-clean-css'),
autoprefixer = require('gulp-autoprefixer');
/*** PATHS ***/
const paths = {
src: {
scss: './src/scss/*.scss',
js: './src/js/*.js',
img: './src/img/*'
},
dist: {
css: './dist/css',
js: './dist/js',
img: './dist/img',
self: './dist/'
}
}
/*** PATHS ***/
/*** FUNCTIONS ***/
const buildSCSS = () => (
gulp.src(paths.src.scss)
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest(paths.dist.css))
.pipe(browserSync.stream())
)
const buildJS = () => (
gulp.src(paths.src.js)
.pipe(concat('scripts.min.js'))
.pipe(gulp.dest(paths.dist.js))
.pipe(browserSync.stream())
)
const buildImg = () => (
gulp.src(paths.src.img)
.pipe(gulp.dest(paths.dist.img))
.pipe(browserSync.stream())
)
const cleanBuild = () => (
gulp.src(paths.dist.self, { allowEmpty: true })
.pipe(clean())
);
const watcher = () => {
browserSync.init({
server: {
baseDir: "./"
}
});
gulp.watch(paths.src.scss, buildSCSS).on("change", browserSync.reload);
gulp.watch(paths.src.js, buildJS).on("change", browserSync.reload);
gulp.watch(paths.src.img, buildImg).on("change", browserSync.reload);
};
const imgMin = () => (
gulp.src(paths.src.img)
.pipe(imagemin())
.pipe(gulp.dest(paths.dist.img))
);
const compresedJS = function () {
return pipeline(
gulp.src(paths.dist.js),
uglify(),
gulp.dest(paths.dist.js));
};
const minifyJS = () => (
gulp.src(paths.dist.js)
.pipe(minifyjs())
.pipe(gulp.dest(paths.dist.js))
);
const minifyCSS = () => (
gulp.src(paths.dist.css)
.pipe(cleanCSS({compatibility: 'ie8'}))
.pipe(gulp.dest(paths.dist.css))
);
const autopref = () => (
gulp.src(paths.dist.css)
.pipe(autoprefixer({
cascade: false
}))
.pipe(gulp.dest(paths.dist.css))
);
/*** TASK ***/
gulp.task('default', gulp.series(
cleanBuild,
imgMin,
buildSCSS,
buildJS,
buildImg,
autopref,
minifyCSS,
buildJS,
compresedJS,
minifyJS,
watcher
));
package.json
{
"name": "",
"version": "1.0.0",
"description": "",
"main": "index.html",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": ""
},
"keywords": [],
"author": "",
"license": "ISC",
"bugs": {
"url": ""
},
"homepage": "",
"devDependencies": {
"browser-sync": "^2.26.14",
"gulp": "^4.0.2",
"gulp-autoprefixer": "^7.0.1",
"gulp-clean": "^0.4.0",
"gulp-clean-css": "^4.3.0",
"gulp-concat": "^2.6.1",
"gulp-imagemin": "^7.1.0",
"gulp-js-minify": "0.0.3",
"gulp-sass": "^4.1.0",
"gulp-uglify": "^3.0.2",
"node-sass": "^5.0.0",
"readable-stream": "^3.6.0"
}
}
В моём случае помог даунгрейд gulp-imagemin до ^7.1.0
Ответ выше в целом о том же самом, просто неявно. Что и мотивировало меня написать ответ. К тому же рейтинг не позволяет отставить комментарий
Моя конфигурация - node 16.13.0, yarn 1.22.5, gulp ^4.0.2
откатил imagemin до 7.1.0 . Заработало.
в терминале npm install [email protected]