logdog90
@logdog90

Поставил плагин gulp-file-include. На выходе, файл index.html собрался криво. Как это пофиксить?

Имеется файл gulpfile.js
const { src, dest, parallel, series, watch } = require('gulp');
const fileinclude = require('gulp-file-include');
const rename = require('gulp-rename');
const autoprefixer = require('gulp-autoprefixer');
const cleanCSS = require('gulp-clean-css');
const sass = require('gulp-sass');
const webpack = require('webpack');
const webpackStream = require('webpack-stream');
const sourcemaps = require('gulp-sourcemaps');
const uglify = require('gulp-uglify-es').default;
const imagemin = require('gulp-imagemin');
const svgSprite = require('gulp-svg-sprite');
const ttf2woff = require('gulp-ttf2woff');
const ttf2woff2 = require('gulp-ttf2woff2');
const fs = require('fs');
const del = require('del');
const browsersync = require('browser-sync').create();
const gutil = require('gulp-util');
const ftp = require('vinyl-ftp');
const path = {
    src: {
        html: [
            'src/*.html'
        ],
        css: './src/sass/**/*.sass',
        js: './src/js/**/*.js',
        img: './src/images/**/*',
        svg: './src/images/**/*.svg',
        fonts: './src/fonts/**',
        fontsStyle: './src/sass/_fonts.sass'
    },
    build: {
        html: 'public/',
        css: './public/css/',
        js: './public/js/',
        fonts: './public/fonts/',
        img: './public/images/'
    },
    watch: {
        html: './src/**/*.html',
        css: './src/sass/**/*.sass',
        js: './src/js/**/*.js',
        img: './src/images/**/*.{png,jpg,jpeg,gif,ico,svg,webp}',
        svg: './src/images/**/*.svg',
        fonts: './src/fonts/**'
    },
    clean: {
        all: './public/**'
    }
};

function htmlInclude() {
    return src(path.src.html)
        .pipe(fileinclude({
            prefix: '@@',
            basepath: '@file'
        }))
        .pipe(dest(path.build.html))
        .pipe(browsersync.stream());
}

const styles = () => {
    return src(path.src.css)
        .pipe(sourcemaps.init())
        .pipe(sass({
            outputStyle: 'expanded'
        }))
        .pipe(rename({
            suffix: '.min'
        }))
        .pipe(autoprefixer({
            overrideBrowserslist: 'last 10 versions',
            grid: true,
            cascade: false
        }))
        .pipe(cleanCSS({
            level: 2
        }))
        .pipe(sourcemaps.write('.'))
        .pipe(dest(path.build.css))
        .pipe(browsersync.stream());
};

const scripts = () => {
    return src(path.src.js)
        .pipe(webpackStream({
            mode: 'development',
            output: {
                filename: 'main.js'
            },
            module: {
                rules: [
                  {
                    test: /\.m?js$/,
                    exclude: /(node_modules|bower_components)/,
                    use: {
                      loader: 'babel-loader',
                      options: {
                        presets: ['@babel/preset-env']
                      }
                    }
                  }
                ]
              }
        }))
        .pipe(sourcemaps.init())
        .pipe(uglify())
        .pipe(sourcemaps.write('.'))
        .pipe(dest(path.build.js))
        .pipe(browsersync.stream());
};

const svgSprites = () => {
    return src(path.src.svg)
        .pipe(svgSprite({
            mode: {
                stack: {
                    sprite: '../sprite.svg'
                }
            }
        }))
        .pipe(dest(path.build.img))
        .pipe(browsersync.stream());
};

const images = () => {
    return src(path.src.img)
        .pipe(imagemin({
            progressive: true,
            svgoPlugins: {
                removeViewBox: false
            },
            interlaced: true,
            optimizationLevel: 3
        }))
        .pipe(dest(path.build.img))
        .pipe(browsersync.stream());
};

const fonts = () => {
    src(path.src.fonts)
        .pipe(ttf2woff())
        .pipe(dest(path.build.fonts))
        .pipe(browsersync.stream());
    src(path.src.fonts)
        .pipe(ttf2woff2())
        .pipe(dest(path.build.fonts))
        .pipe(browsersync.stream());
    return src(path.src.fonts)
        .pipe(dest(path.build.fonts));
};

const cb = () => {};

let srcFonts = path.src.fontsStyle;
let appFonts = path.build.fonts;

const fontsStyle = (done) => {
    let filecontent = fs.readFileSync(srcFonts);

    fs.writeFile(srcFonts, '', cb);
    fs.readdir(appFonts, function (err, items) {
        if (items) {
            let cFontName;
            for (var i = 0; i < items.length; i++) {
                let fontname = items[i].split('.');
                fontname = fontname[0];
                if (cFontName != fontname) {
                    fs.appendFile(srcFonts, '@include font-face("' + fontname + '", "' + fontname + '", 400)\r\n', cb);
                }
                cFontName = fontname;
            }
        }
    });

    done();
};

const clean = () => {
    return del(path.clean.all);
};

const startWatch = () => {
    browsersync.init({
        server: {
            baseDir: path.build.html
        },
        notify: false,
        // online: true
    });
    watch(path.watch.html, htmlInclude);
    watch(path.watch.css, styles);
    watch(path.watch.js, scripts);
    watch(path.watch.svg, svgSprites);
    watch(path.watch.img, images);
    watch(path.watch.fonts, fonts);
    watch(path.watch.fonts, fontsStyle);
};

const deploy = () => {
    let conn = ftp.create({
        host: '',
        user: '',
        password: '',
        parallel: 10,
        log: gutil.log
    });

    let globs = [
        path.clean.all,
    ];

    return src(globs, {
        base: path.build.html,
        buffer: false
    })
        .pipe(conn.newer('')) // only upload newer files
        .pipe(conn.dest(''));
};

exports.htmlInclude = htmlInclude;
exports.styles = styles;
exports.scripts = scripts;
exports.startWatch = startWatch;
exports.deploy = deploy;
exports.default = series(clean, parallel(htmlInclude, scripts, fonts, images, svgSprites), fontsStyle, styles, startWatch);


Имеется файл index.html который находится в корне папки ./src/
<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="css/main.min.css">
    <title>START-TEMPLATE</title>
</head>
<body>
    @@include('html/header.html')
    <h1>Жил-был у бабушке серенький козлик!</h1>
    <svg class="">
        <use xlink:href="images/sprite.svg#svg"></use>
    </svg>
    @@include('html/footer.html')

    <script src="js/main.js"></script>
</body>
</html>


В gulpfile.js установил плагин gulp-file-include по документации gulp 4
function htmlInclude() {
    return src(path.src.html)
        .pipe(fileinclude({
            prefix: '@@',
            basepath: '@file'
        }))
        .pipe(dest(path.build.html))
        .pipe(browsersync.stream());
}


На выходе в корне папки ./public/index.html получается такая хрень
<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="css/main.min.css">
    <title>START-TEMPLATE</title>
</head>
<body>
    <!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    <h1 class="title">Шапка сайта</h1>
</body>
</html>
    <h1>Жил-был у бабушке серенький козлик!</h1>
    <svg class="">
        <use xlink:href="images/sprite.svg#svg"></use>
    </svg>
    <!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    <h1 class="title">Футер сайта</h1>
</body>
</html>

    <script src="js/main.js"></script>
</body>
</html>


Естественно файлы header.html и footer.html я подключил правильно, поскольку на выходе я бы не получил index.html
Как мне это пофиксить, а именно чтобы плагин gulp-file-include на выходе выплёвывал корректный файл index.html без повторяющихся тегов?
  • Вопрос задан
  • 602 просмотра
Решения вопроса 1
logdog90
@logdog90 Автор вопроса
В файле header.html
<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    <h1>Шапка сайта</h1>
</body>
</html>


В файле footer.html
<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    <h1>Футер сайта</h1>
</body>
</html>
Ответ написан
Пригласить эксперта
Ответы на вопрос 1
@MaxGraph
Web-разработчик, верстальщик
А что в файлах header и footer?
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы