Помогите корректно встроить скрипт в сборку gulp
Я пытаюсь сверстать слайдер из урока по верстке (1:22:00). Использую сборку gulp отсюда. На всякий случай, код gulpFule.js:
let project_folder = require("path").basename(__dirname);
let source_folder = "#src";
let path={
build: {
html: project_folder + "/",
css: project_folder + "/css/",
js: project_folder + "/js/",
img: project_folder + "/img/",
fonts: project_folder + "/fonts/",
},
src: {
html: [source_folder + "/*.html", "!" + source_folder + "/_*.html"],
css: source_folder + "/scss/style.scss",
js: source_folder + "/js/script.js",
img: source_folder + "/img/**/*.{jpg,png,svg,gif,ico,webp}",
fonts: source_folder + "/fonts/*.ttf",
},
watch: {
html: source_folder + "/**/*.html",
css: source_folder + "/scss/**/*.scss",
js: source_folder + "/js/**/*.js",
img: source_folder + "/img/**/*.{jpg,png,svg,gif,ico,webp}",
},
clean: "./" + project_folder + "/"
}
let {src,dest} = require("gulp"),
gulp = require("gulp"),
browsersync = require("browser-sync").create(),
fileinclude = require("gulp-file-include"),
del = require("del"),
scss = require("gulp-sass"),
autoprefixer = require("gulp-autoprefixer"),
group_media = require("gulp-group-css-media-queries"),
clean_css = require("gulp-clean-css"),
rename = require("gulp-rename"),
uglify = require("gulp-uglify-es").default,
imagemin = require("gulp-imagemin"),
webp = require("gulp-webp"),
webphtml = require("gulp-webp-html"),
webpcss = require("gulp-webpcss"),
ttf2woff = require("gulp-ttf2woff"),
ttf2woff2 = require("gulp-ttf2woff2"),
fonter = require("gulp-fonter");
function browserSync(params) {
browsersync.init({
server:{
baseDir: "./" + project_folder + "/"
},
port: 3000,
notify: false
})
}
function html() {
return src(path.src.html)
.pipe(fileinclude())
.pipe(webphtml())
.pipe(dest(path.build.html))
.pipe(browsersync.stream())
}
function css() {
return src(path.src.css)
.pipe(
scss({
outputStyle: "expanded"
})
)
.pipe(
group_media()
)
.pipe(
autoprefixer({
overrideBrowserslist: ["last 5 version"],
cascade: true
})
)
.pipe(webpcss())
.pipe(dest(path.build.css))
.pipe(clean_css())
.pipe(
rename({
extname: ".min.css"
})
)
.pipe(dest(path.build.css))
.pipe(browsersync.stream())
}
function js() {
return src(path.src.js)
.pipe(fileinclude())
.pipe(dest(path.build.js))
.pipe(
uglify()
)
.pipe(
rename({
extname: ".min.js"
})
)
.pipe(dest(path.build.js))
.pipe(browsersync.stream())
}
function images() {
return src(path.src.img)
.pipe(
webp({
quality:70
})
)
.pipe(dest(path.build.img))
.pipe(src(path.src.img))
.pipe(
imagemin({
progressive: true,
svgoPlugins: [{ removeViewBox: false}],
interlaced: true,
optmizationLevel: 3
})
)
.pipe(dest(path.build.img))
.pipe(browsersync.stream())
}
function fonts() {
src(path.src.fonts)
.pipe(ttf2woff())
.pipe(dest(path.build.fonts));
return src(path.src.fonts)
.pipe(ttf2woff2())
.pipe(dest(path.build.fonts));
};
gulp.task('otf2ttf', function () {
return gulp.src([source_folder + '/fonts/*otf'])
.pipe(fonter({
formats: ['ttf']
}))
.pipe(dest(source_folder + '/fonts/'));
})
const fs = require('fs');
function fontsStyle(params) {
let file_content = fs.readFileSync(source_folder + '/scss/fonts.scss', 'utf-8');
if (file_content == '') {
fs.writeFile(source_folder + '/scss/fonts.scss', '', cb);
return fs.readdir(path.build.fonts, function (err, items) {
if (err){
console.log(err);
}
if (items) {
let c_fontname;
for (var i = 0; i < items.length; i++) {
let fontname = items[i].split('.');
fontname = fontname[0];
if (c_fontname != fontname) {
fs.appendFile(source_folder + '/scss/fonts.scss', '@include font("' + fontname + '", "' + fontname + '", "400", "normal");\r\n', cb);
}
c_fontname = fontname;
}
}
})
}
}
function cb() { }
function watchfile(params) {
gulp.watch([path.watch.html], html);
gulp.watch([path.watch.css], css);
gulp.watch([path.watch.js], js);
gulp.watch([path.watch.img], images);
}
function clean(params) {
return del(path.clean);
}
let build = gulp.series(clean, gulp.parallel(js, css, html, images, fonts), fontsStyle);
let watch = gulp.parallel(build,watchfile,browserSync);
exports.fontsStyle = fontsStyle;
exports.fonts = fonts;
exports.images = images;
exports.js = js;
exports.css = css;
exports.html = html;
exports.build = build;
exports.watch = watch;
exports.default = watch;
Как я понял автор использует свой js метод для того, чтобы установить img фоном в слайдер, т.к. IE11 не поддерживает css свойство background Cтили и скрипт метода взял отсюда и немного поменял js. Теперь приведу весь код слайдера, который есть на данный момент. Разметка:
<main class="page">
<div class="main-slider">
<div class="main-slider__body">
<div class="main-slider__item item-main-slider">
<div class="item-main-slider__content">
<div class="item-main-slider__container _container">
<div class="title">
<div class="title__item">Только эксклюзивные</div>
<div class="title__main title__main-white title__main-regular">Лоты под аукцион и свободную продажу</div>
</div>
<div class="main-slider-item__text">Мы собираем эксклюзивную публику и экслюзивные лоты, даем удобный и автоматизированный сервис по покупке и продаже, а также выставлению лотов на аукцион, предоставляем личные кабинеты, а также оказываем сопутствубщие услуги с продажей редких и дорогих вещей</div>
</div>
</div>
<div class="item-main-slider__bg _ibg">
<img src="img/main-slider/01.png" alt="">
</div>
</div>
</div>
<div class="main-slider__control"></div>
</div>
</main>
null.scss:
* {
padding: 0;
margin: 0;
border: 0;
}
*,
*:before,
*:after {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
:focus,
:active {
outline: none;
}
a:focus,
a:active {
outline: none;
}
nav,
footer,
header,
aside {
display: block;
}
html,
body {
height: 100%;
width: 100%;
font-size: 100%;
line-height: 1;
font-size: 14px;
-ms-text-size-adjust: 100%;
-moz-text-size-adjust: 100%;
-webkit-text-size-adjust: 100%;
font-family: $font-family;
}
input,
button,
textarea {
font-family: inherit;
}
input::-ms-clear {
display: none;
}
button {
cursor: pointer;
}
button::-moz-focus-inner {
padding: 0;
border: 0;
}
a,
a:visited {
text-decoration: none;
}
a:hover {
text-decoration: none;
}
ul li {
list-style: none;
}
img {
vertical-align: top;
}
h1,
h2,
h3,
h4,
h5,
h6 {
font-size: inherit;
font-weight: 400;
}
style.scss:
@mixin font($font_name, $file_name, $weight, $style) {
@font-face {
font-family: $font_name;
font-display: swap;
src: url("../fonts/#{$file_name}.woff") format("woff"), url("../fonts/#{$file_name}.woff2") format("woff2");
font-weight: #{$weight};
font-style: #{$style};
}
}
@import "fonts.scss";
//Шрифт по умолчанию================================================================================================
$font-family: "PT Sans";
//Шрифт по умолчанию================================================================================================
// ПЕРЕМЕННЫЕ ======================================================================================================
$minwidth : 320px;
$mw : 950;
$md1 : $mw+12;
$md2 : 991.98;
$md3 : 767.98;
$md4 : 479.98;
//ПЕРЕМЕННЫЕ========================================================================================================
// Обнуление общие стили============================================================================================
@import "null.scss";
body {
color: #000;
font-size: 14px;
&._lock{
overflow: hidden;
@media (max-width: $md3+px) {
// width: 100%;
// position: fixed;
overflow: hidden;
}
}
}
//=================================================================================================================
// Обертка ========================================================================================================
.wrapper {
width: 100%;
min-height: 100%;
overflow: hidden;
display: flex;
flex-direction: column;
&._loaded{
}
}
//=================================================================================================================
// Основная сетка =================================================================================================
._container {
max-width: $mw+px;
margin: 0 auto;
@media (max-width: $md1+px) {
max-width: 970px;
}
@media (max-width: $md2+px) {
max-width: 750px;
}
@media (max-width: $md3+px) {
max-width: none;
padding: 0 10px;
}
}
.page {
display: flex;
flex: 1 1 auto;
}
// ================================================================================================================
// main slider
.main-slider {}
.main-slider__body {}
.main-slider__item {}
.item-main-slider {
position: relative;
padding: 30px 0 100px 0;
text-align: center;
}
.item-main-slider__content {
position: relative;
z-index: 2;
}
.item-main-slider__container {}
.title {}
.title__item {
font-family: "ceremonious";
font-size: 40px;
color: #bb9c66;
}
.title__main {
font-size: 35px;
text-transform: uppercase;
font-family: "pfdin";
font-weight: 500;
}
.title__main-white{
color: #fff;
}
.title__main-regular{
font-weight: 400;
}
.main-slider-item__text {
color: #fff;
font-size: 15px;
line-height: calc(25/15);
max-width: 700px;
margin: 0 auto;
}
.item-main-slider__bg {
position: relative;
width: 100%;
height: 100%;
left: 0;
top: 0;
}
._ibg{
background-position: center;
background-size: cover;
background-repeat: no-repeat;
position: relative;
img{
width: 0;
height: 0;
position: absolute;
top: 0;
left: 0;
opacity: 0;
visibility: hidden;
}
}
.main-slider__control {}
Ну и js:
function testWebP(callback) {
var webP = new Image();
webP.onload = webP.onerror = function () {
callback(webP.height == 2);
};
webP.src = "data:image/webp;base64,UklGRjoAAABXRUJQVlA4IC4AAACyAgCdASoCAAIALmk0mk0iIiIiIgBoSygABc6WWgAA/veff/0PP8bA//LwYAAA";
}
testWebP(function (support) {
if (support == true) {
document.querySelector('body').classList.add('webp');
}else{
document.querySelector('body').classList.add('no-webp');
}
});
function ibg(){
let ibg=document.querySelectorAll("._ibg");
for (var i = 0; i < ibg.length; i++) {
if(ibg[i].querySelector('img')){
if(document.querySelector('body').classList.contains("no-webp")){
ibg[i].style.backgroundImage = 'url('+ibg[i].querySelector('img').getAttribute('src')+')';
}
else{
let path = ""+ibg[i].querySelector('img').getAttribute('src').split('.')[0]+".webp";
ibg[i].style.backgroundImage = 'url('+path+')';
}
}
}
}
ibg();
У меня получается следующее:
Если навести курсор на div с классом item-main-slider, то увидим, что он размера 720x0, а еще почему-то тег picture сформированный gulp-ом, имеет размер 0x0. Помогите это исправить. Надеюсь, я опубликовал достаточно кода, чтобы вы смогли запустить сборку.
