Почему gulp не видит изображения?

Ссылка скопирована
1 ответ

:Пишет ошибку
Failed to load resource: the server responded with a status of 404 (Not Found)
И не загружает изображение, хотя когда я открываю в дисте, все норм

Вот код:

"use strict"  const { src, dest } = require("gulp") const gulp = require("gulp") const autoprefixer = require("gulp-autoprefixer") const cssbeautify = require("gulp-cssbeautify"); const removeComments = require('gulp-strip-css-comments'); const rename = require("gulp-rename"); const rigger = require("gulp-rigger") const sass = require("gulp-sass")(require('sass')); const cssnano = require("gulp-cssnano"); const uglify = require("gulp-uglify"); const plumber = require("gulp-plumber"); const panini = require("panini"); const imagemin = require("gulp-imagemin"); const del = require("del"); const notify = require("gulp-notify") const browserSync = require("browser-sync").create(); const pugFile = require("gulp-pug"); const imagewebp = require("gulp-webp") const webpHtml = require("gulp-webp-html");   /* Paths */ const srcPath = "src/" const distPath = "dist/"   const path = {     build: {         pug: distPath,         css: distPath + "assets/css/",         js: distPath + "assets/js/",         images: distPath + "assets/img/",         fonts: distPath + "assets/fonts/"     },     src: {         pug: srcPath + "pug/*.pug",         css: srcPath + "assets/scss/*.scss",         js: srcPath + "assets/js/*.js",         images: srcPath + "assets/img/**/*.{jpg,jpeg,png,svg,gif,ico,webp,webmanifest,xml,json}",         fonts: srcPath + "assets/fonts/**/*.{eot,woff,woff2,ttf,svg}"     },     watch: {         pug: srcPath + "pug/**/*.pug",         js: srcPath + "assets/js/**/*.js",         css: srcPath + "assets/scss/**/*.scss",         images: srcPath + "assets/img/**/*.{jpg,jpeg,png,svg,gif,ico,webp,webmanifest,xml,json}",         fonts: srcPath + "assets/fonts/**/*.{eot,woff,woff2,ttf,svg}"     },     clean: "./" + distPath }  function serve() {     browserSync.init({         server: {             baseDir: "./dist/pug/"         }     }); }   function pug() {     return src(path.src.pug, { base: srcPath })         .pipe(pugFile({             pretty: true         }))         .pipe(plumber({             errorHandler: function (err) {                 notify.onError({                     title: "PUG Error",                     message: "Error: <%= error.message %>"                 })(err);                 this.emit('end');             }         }))         .pipe(webpHtml())         .pipe(dest(path.build.pug))         .pipe(browserSync.reload({ stream: true })); }   function css() {     return src(path.src.css, { base: srcPath + "assets/scss/" })         .pipe(plumber({             errorHandler: function (err) {                 notify.onError({                     title: "SCSS Error",                     message: "Error: <%= error.message %>"                 })(err);                 this.emit('end');             }         }))         .pipe(sass())         .pipe(autoprefixer())         .pipe(cssbeautify())         .pipe(dest(path.build.css))         .pipe(cssnano({             zindex: false,             discardComments: {                 removeAll: true             }         }))         .pipe(removeComments())         .pipe(rename({             suffix: ".min",             extname: ".css"         }))         .pipe(dest(path.build.css))         .pipe(browserSync.reload({ stream: true })); }  function js() {     return src(path.src.js, { base: srcPath + "assets/js/" })         .pipe(plumber({             errorHandler: function (err) {                 notify.onError({                     title: "JS Error",                     message: "Error: <%= error.message %>"                 })(err);                 this.emit('end');             }         }))         .pipe(rigger())         .pipe(dest(path.build.js))         .pipe(uglify())         .pipe(rename({             suffix: ".min",             extname: ".js"         }))         .pipe(dest(path.build.js))         .pipe(browserSync.reload({ stream: true })); }  function images() {     return src(path.src.images, { base: srcPath + "assets/img/" })         .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(path.build.images))         .pipe(imagewebp())         .pipe(dest(path.build.images))         .pipe(browserSync.reload({ stream: true })); }   function fonts() {     return src(path.src.fonts, { base: srcPath + "assets/fonts/" })         .pipe(dest(path.build.fonts))         .pipe(browserSync.reload({ stream: true })); }  function clean() {     return del(path.clean) }  function watchFiles() {     gulp.watch([path.watch.pug], pug)     gulp.watch([path.watch.css], css)     gulp.watch([path.watch.js], js)     gulp.watch([path.watch.images], images)     gulp.watch([path.watch.fonts], fonts) }  const build = gulp.series(clean, gulp.parallel(pug, css, js, images, fonts)) const watch = gulp.parallel(build, watchFiles, serve)     exports.pug = pug exports.css = css exports.js = js exports.images = images exports.fonts = fonts exports.clean = clean exports.build = build exports.watch = watch exports.default = watch

"use strict" const { src, dest } = require("gulp") const gulp = require("gulp") const autoprefixer = require("gulp-autoprefixer") const cssbeautify = require("gulp-cssbeautify"); const removeComments = require('gulp-strip-css-comments'); const rename = require("gulp-rename"); const rigger = require("gulp-rigger") const sass = require("gulp-sass")(require('sass')); const cssnano = require("gulp-cssnano"); const uglify = require("gulp-uglify"); const plumber = require("gulp-plumber"); const panini = require("panini"); const imagemin = require("gulp-imagemin"); const del = require("del"); const notify = require("gulp-notify") const browserSync = require("browser-sync").create(); const pugFile = require("gulp-pug"); const imagewebp = require("gulp-webp") const webpHtml = require("gulp-webp-html"); /* Paths */ const srcPath = "src/" const distPath = "dist/" const path = { build: { pug: distPath, css: distPath + "assets/css/", js: distPath + "assets/js/", images: distPath + "assets/img/", fonts: distPath + "assets/fonts/" }, src: { pug: srcPath + "pug/*.pug", css: srcPath + "assets/scss/*.scss", js: srcPath + "assets/js/*.js", images: srcPath + "assets/img/**/*.{jpg,jpeg,png,svg,gif,ico,webp,webmanifest,xml,json}", fonts: srcPath + "assets/fonts/**/*.{eot,woff,woff2,ttf,svg}" }, watch: { pug: srcPath + "pug/**/*.pug", js: srcPath + "assets/js/**/*.js", css: srcPath + "assets/scss/**/*.scss", images: srcPath + "assets/img/**/*.{jpg,jpeg,png,svg,gif,ico,webp,webmanifest,xml,json}", fonts: srcPath + "assets/fonts/**/*.{eot,woff,woff2,ttf,svg}" }, clean: "./" + distPath } function serve() { browserSync.init({ server: { baseDir: "./dist/pug/" } }); } function pug() { return src(path.src.pug, { base: srcPath }) .pipe(pugFile({ pretty: true })) .pipe(plumber({ errorHandler: function (err) { notify.onError({ title: "PUG Error", message: "Error: <%= error.message %>" })(err); this.emit('end'); } })) .pipe(webpHtml()) .pipe(dest(path.build.pug)) .pipe(browserSync.reload({ stream: true })); } function css() { return src(path.src.css, { base: srcPath + "assets/scss/" }) .pipe(plumber({ errorHandler: function (err) { notify.onError({ title: "SCSS Error", message: "Error: <%= error.message %>" })(err); this.emit('end'); } })) .pipe(sass()) .pipe(autoprefixer()) .pipe(cssbeautify()) .pipe(dest(path.build.css)) .pipe(cssnano({ zindex: false, discardComments: { removeAll: true } })) .pipe(removeComments()) .pipe(rename({ suffix: ".min", extname: ".css" })) .pipe(dest(path.build.css)) .pipe(browserSync.reload({ stream: true })); } function js() { return src(path.src.js, { base: srcPath + "assets/js/" }) .pipe(plumber({ errorHandler: function (err) { notify.onError({ title: "JS Error", message: "Error: <%= error.message %>" })(err); this.emit('end'); } })) .pipe(rigger()) .pipe(dest(path.build.js)) .pipe(uglify()) .pipe(rename({ suffix: ".min", extname: ".js" })) .pipe(dest(path.build.js)) .pipe(browserSync.reload({ stream: true })); } function images() { return src(path.src.images, { base: srcPath + "assets/img/" }) .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(path.build.images)) .pipe(imagewebp()) .pipe(dest(path.build.images)) .pipe(browserSync.reload({ stream: true })); } function fonts() { return src(path.src.fonts, { base: srcPath + "assets/fonts/" }) .pipe(dest(path.build.fonts)) .pipe(browserSync.reload({ stream: true })); } function clean() { return del(path.clean) } function watchFiles() { gulp.watch([path.watch.pug], pug) gulp.watch([path.watch.css], css) gulp.watch([path.watch.js], js) gulp.watch([path.watch.images], images) gulp.watch([path.watch.fonts], fonts) } const build = gulp.series(clean, gulp.parallel(pug, css, js, images, fonts)) const watch = gulp.parallel(build, watchFiles, serve) exports.pug = pug exports.css = css exports.js = js exports.images = images exports.fonts = fonts exports.clean = clean exports.build = build exports.watch = watch exports.default = watch

Дополнительно:

https://yandex.ru/search/?text=почему+возникает+ош...

  • const srcPath = "src/" const distPath = "dist/"

    const srcPath = "src/" const distPath = "dist/"

    У вас пути будут относительно текущей страницы. Если открыта не главная страница, то модуль будет работать не так, как вы ожидаете.
    Для подтверждения моей догадки посмотрите на путь к изображению там, где вышла ошибка.

  • Нужно решить такую задачу?

    Опишите проблему, и специалист поможет с настройкой, исправлением ошибки или доработкой сайта. Подберём понятный план работ без лишней переписки.

    Заказать помощь
    Лучший ответ
    1
    Кирилл JS Ответ

    Проблема может возникнуть из-за нескольких возможных причин. Вот несколько шагов, которые можно предпринять для решения проблемы:

    1. Проверьте правильность путей к изображениям в вашем проекте. Убедитесь, что пути указаны правильно и что изображения находятся в указанных каталогах.

    2. Убедитесь, что ваши изображения не исключены из процесса сборки Gulp. Проверьте конфигурацию Gulp и убедитесь, что плагины, которые вы используете, не исключают изображения из обработки.

    3. Проверьте наличие ошибок при сборке проекта. Запустите процесс сборки Gulp с флагом --verbose, чтобы увидеть более подробные сообщения об ошибках.

    4. Попробуйте сбросить кеш Gulp и перезапустить процесс сборки. Иногда проблемы могут возникать из-за некорректного кеширования файлов.

    Приведенные выше шаги могут помочь вам выявить и решить проблему с отображением изображений в Gulp. Если проблема сохраняется, обратитесь к документации плагинов, которые вы используете, или к сообществу разработчиков для получения дополнительной помощи.

    Другие ответы (0)

    Пока нет других ответов. Будьте первым, кто поможет автору.

    Ответить на вопрос

    комментарий

    Ваш адрес email не будет опубликован. Обязательные поля помечены *

    Вам также может быть интересно