I'm trying to import custom fonts using Gulp and Sass, but i can't figure out how.
For now, i've tried many things :
Create a mixin
#mixin font-face($font-family, $file-path, $font-weight, $font-style) {
#font-face {
font-family: $font-family;
src: url("#{$file-path}.eot");
src: url("#{$file-path}.eot?#iefix") format("embedded-opentype"),
url("#{$file-path}.woff") format("woff"),
url("#{$file-path}.ttf") format("truetype"),
url("#{$file-path}.svg##{$font-family}") format("svg");
font-weight: $font-weight;
font-style: $font-style;
}
// Chrome for Windows rendering fix: http://www.adtrak.co.uk/blog/font-face-chrome-rendering/
#media screen and (-webkit-min-device-pixel-ratio: 0) {
#font-face {
font-family: $font-family;
src: url("#{$file-path}.svg##{$font-family}") format("svg");
}
}
}
Then in my main scss file, i've included it like so
/* Include custom fonts */
#include font-face(
"Myfont-Regular",
"../../src/fonts/Myfont-Regu",
400,
normal
);
#include font-face(
"Myfont-Bold",
"../../src/fonts/Myfont-Bold",
700,
bold
);
#include font-face(
"Myfont-Black",
"../../src/fonts/Myfont-BlacExte",
900,
normal
);
/* End custom fonts include */
///Defining Font Family
$body-font-regular: "Myfont-Regular", Arial, Helvetica, sans-serif;
$body-font-bold: "Myfont-Bold", Arial, Helvetica, sans-serif;
$body-font-black: "Myfont-Black", Arial, Helvetica, sans-serif;
I think the main problem comes from my .gulpfile, but i can't find out where (i'm just starting using gulp, so i made it out of snippets i found). I've created a gulp task to copy the font folder but i'm not sure how to make it work. Here is my gulpfile :
"use strict";
/*global require*/
const autoprefixer = require("autoprefixer");
const babel = require("gulp-babel");
const browserSync = require("browser-sync");
const changed = require("gulp-changed");
const concat = require("gulp-concat");
const data = require("gulp-data");
const del = require("del");
const gulp = require("gulp");
const gulpif = require("gulp-if");
const imagemin = require("gulp-imagemin");
const path = require("path");
const plumber = require("gulp-plumber");
const postcss = require("gulp-postcss");
const pug = require("gulp-pug");
const runSequence = require("run-sequence");
const sass = require("gulp-sass");
const sourcemaps = require("gulp-sourcemaps");
const uglify = require("gulp-uglify");
/**
* List of options
*/
const options = {
uglifyJS: true,
sourceMaps: true,
useBabel: true
};
/*
* List of directories
*/
const paths = {
input: {
sass: "./src/sass/",
data: "./src/_data/",
js: "./src/js/",
images: "./src/img/",
fonts: "./src/fonts"
},
output: {
css: "./public/css/",
js: "./public/js/",
images: "./public/img/",
fonts: "./public/fonts"
},
public: "./public/"
};
/************************
* Gulp Tasks *
************************/
/**
* Concat all scripts and make sourcemap (optional)
* Scripts from vendor folder added first
*/
gulp.task("javascript", function() {
return gulp
.src([paths.input.js + "vendor/**/*.js", paths.input.js + "**/*.js"])
.pipe(plumber())
.pipe(gulpif(options.sourceMaps, sourcemaps.init()))
.pipe(
gulpif(
options.useBabel,
babel({
presets: ["#babel/preset-env"]
})
)
)
.pipe(concat("script.js"))
.pipe(gulpif(options.uglifyJS, uglify()))
.pipe(gulpif(options.sourceMaps, sourcemaps.write("../maps")))
.pipe(gulp.dest(paths.output.js))
.pipe(
browserSync.reload({
stream: true
})
);
});
/*
* Minify all images
*/
gulp.task("image-min", function() {
return gulp
.src(paths.input.images + "**/*.+(png|jpg|gif|svg|jpeg)")
.pipe(plumber())
.pipe(changed(paths.output.images))
.pipe(imagemin())
.pipe(gulp.dest(paths.output.images));
});
/**
* Compile .pug files and pass in data from json file
* Example: index.pug - index.pug.json
*/
gulp.task("pug", function() {
return gulp
.src("./src/*.pug")
.pipe(plumber())
.pipe(
data(function(file) {
const json = paths.input.data + path.basename(file.path) + ".json";
delete require.cache[require.resolve(json)];
return require(json);
})
)
.pipe(pug({ pretty: true }))
.pipe(gulp.dest(paths.public))
.pipe(
browserSync.reload({
stream: true
})
);
});
/**
* Removing public folder with it contents
*/
gulp.task("build-clean", function() {
return del(paths.public);
});
/**
* Recompile .pug files and live reload the browser
*/
gulp.task("rebuild", ["pug"], function() {
browserSync.reload();
});
/**
* Launch the browser-sync Server
*/
gulp.task("browser-sync", function() {
browserSync({
server: {
baseDir: paths.public
},
notify: false
});
});
/**
* Copy custom font folder
*/
gulp.task("copy", ["clean"], function() {
return gulp
.src(["src/fonts/*"], {
base: "src"
})
.pipe(gulp.dest("public"));
});
/**
* Task group for development
*/
gulp.task("develop", function() {
runSequence(
"build-clean",
["sass", "javascript", "image-min", "pug"],
"browser-sync"
);
});
/**
* Building distributive
*/
gulp.task("build-dist", function() {
runSequence("build-clean", ["sass", "javascript", "image-min", "pug"]);
});
/**
* Compile .scss files
* Autoprefixer
* Sourcemaps (optional)
*/
gulp.task("sass", function() {
return gulp
.src(paths.input.sass + "*.scss")
.pipe(plumber())
.pipe(gulpif(options.sourceMaps, sourcemaps.init()))
.pipe(
sass({
includePaths: [paths.input.sass],
outputStyle: "compressed"
})
)
.pipe(postcss([autoprefixer()]))
.pipe(gulpif(options.sourceMaps, sourcemaps.write("../maps")))
.pipe(gulp.dest(paths.output.css))
.pipe(
browserSync.reload({
stream: true
})
);
});
/**
* Watch files for changes
*/
gulp.task("watch", function() {
gulp.watch(paths.input.sass + "**/*.scss", ["sass"]);
gulp.watch(paths.input.js + "**/*.js", ["javascript"]);
gulp.watch(paths.input.images + "**/*", ["image-min"]);
gulp.watch(["./src/**/*.pug", "./src/**/*.json"], ["pug"]);
});
/**
* Shorthand for build-dist
*/
gulp.task("build", ["build-dist"]);
/**
* Default task for development, fast-start by 'gulp' command
*/
gulp.task("default", ["develop", "watch"]);
By the way, here is my project folder structure :
Related
I am new to scss and I am trying to make use of bootstrap 5. so far I have managed to define a primary color, i seem to have run into this problem here Customizing bootstrap 5 button colors and properties in it the background is red but the color of the text is black and i cannot seem to change it
This is what I have in src/main.scss
// Variable overrides for bootstrap
$primary: #fa2152;
// $secondary: ;
// $success:
// $info:
// $warning:
// $danger:
$light: #d8d8d8;
// $dark:
.btn-primary {
color: #fff;
}
#import "../node_modules/bootstrap/scss/bootstrap";
my rollup file
import svelte from 'rollup-plugin-svelte';
import commonjs from '#rollup/plugin-commonjs';
import resolve from '#rollup/plugin-node-resolve';
import livereload from 'rollup-plugin-livereload';
import { terser } from 'rollup-plugin-terser';
import sveltePreprocess from 'svelte-preprocess';
import typescript from '#rollup/plugin-typescript';
import css from 'rollup-plugin-css-only';
import json from '#rollup/plugin-json';
import replace from '#rollup/plugin-replace';
import scss from "rollup-plugin-scss";
const production = !process.env.ROLLUP_WATCH;
const site = process.env.SITE || 'defaults';
function serve() {
let server;
function toExit() {
if (server) server.kill(0);
}
return {
writeBundle() {
if (server) return;
server = require('child_process').spawn('npm', ['run', 'start', '--', '--dev'], {
stdio: ['ignore', 'inherit', 'inherit'],
shell: true
});
process.on('SIGTERM', toExit);
process.on('exit', toExit);
}
};
}
export default {
input: 'src/main.ts',
output: {
sourcemap: !production,
format: 'iife',
name: 'app',
file: 'public/build/bundle.js'
},
plugins: [
replace({
'process.env.NODE_ENV': JSON.stringify('production'),
'process.env.SITE': JSON.stringify(site),
}),
svelte({
preprocess: sveltePreprocess({
sourceMap: !production,
// defaults: {
// style: 'scss'
// },
postcss: {
plugins: [
// require("tailwindcss"),
require("autoprefixer"),
],
},
}),
compilerOptions: {
// enable run-time checks when not in production
dev: !production
},
emitCss: true,
}),
scss({watch: 'src', output: 'public/build/bootstrap.css'}),
// we'll extract any component CSS out into
// a separate file - better for performance
css({ output: 'bundle.css'}),
// If you have external dependencies installed from
// npm, you'll most likely need these plugins. In
// some cases you'll need additional configuration -
// consult the documentation for details:
// https://github.com/rollup/plugins/tree/master/packages/commonjs
resolve({
browser: true,
dedupe: ['svelte']
}),
commonjs(),
typescript({
sourceMap: !production,
inlineSources: !production
}),
json(),
// In dev mode, call `npm run start` once
// the bundle has been generated
!production && serve(),
// Watch the `public` directory and refresh the
// browser on changes when not in production
!production && livereload('public'),
// If we're building for production (npm run build
// instead of npm run dev), minify
production && terser()
],
watch: {
clearScreen: false
}
};
my public/index.html contains
<link rel='icon' type='image/png' href='/favicon.png'>
<!-- <link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> -->
<link rel='stylesheet' href='/build/bootstrap.css'>
<link rel='stylesheet' href='/global.css'>
<link rel='stylesheet' href='/build/bundle.css'>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<script defer src='/build/bundle.js'></script>
I want to make the color of the button white.
in src/main.ts i do
import "./main.scss";
import App from "./App.svelte";
const app = new App({
target: document.body,
props: {},
});
export default app;
I'm trying to deploy the following starter kit on Heroku. However, when I try to start it, it fails :(
Error:
Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch
I did not find anywhere to configure or set the port. It's launching on 8080 however it still fails.
Browser-sync-server:
/**
* Start browserSync server
*/
'use strict';
const fs = require('fs');
module.exports = function(options) {
return () => {
// If index.html exist - open it, else show folder
let listDirectory = fs.existsSync(options.mainHtml) ? false : true;
options.browserSync.init({
notify: false,
server: {
baseDir: './',
directory: listDirectory
},
snippetOptions: {
// Provide a custom Regex for inserting the snippet
rule: {
match: /$/i,
fn: (snippet, match) => snippet + match
}
},
port: 8080
});
};
};
Package.json:
{
"name": "Demo-app",
"version": "2.3.2",
"description": "Demo Project",
"repository": {
"type": "git",
},
"keywords": [
"starte",
"markup",
"JustCoded",
"jc"
],
"author": "JustCoded",
"license": "MIT",
"bugs": {
},
"devDependencies": {
"#babel/core": "^7.5.5",
"#babel/preset-env": "^7.5.5",
"babelify": "^10.0.0",
"browser-sync": "^2.18.0",
"browserify": "^16.5.0",
"del": "^3.0.0",
"eslint-config-airbnb-base": "^14.0.0",
"eslint-plugin-import": "^2.14.0",
"files-exist": "^1.1.0",
"gulp": "^4.0.0",
"gulp-autoprefixer": "^4.0.0",
"gulp-concat": "^2.6.1",
"gulp-cssimport": "^5.0.0",
"gulp-cssnano": "^2.1.2",
"gulp-debug": "^3.1.0",
"gulp-eslint": "^5.0.0",
"gulp-file-include": "^2.0.1",
"gulp-group-css-media-queries": "^1.2.0",
"gulp-htmlhint": "^0.3.1",
"gulp-if": "^2.0.2",
"gulp-imagemin": "^4.1.0",
"gulp-newer": "^1.3.0",
"gulp-notify": "^3.0.0",
"gulp-rename": "^1.2.2",
"gulp-sass": "^4.0.2",
"gulp-sourcemaps": "^2.4.1",
"gulp-uglify": "^3.0.0",
"htmlhint-stylish": "^1.0.3",
"node-notifier": "^5.0.2",
"path": "^0.12.7",
"vinyl-source-stream": "^2.0.0"
},
"engines": {
"node": ">=6.0.0"
},
"scripts": {
"test": "gulp build",
"production": "gulp build",
"start": "gulp"
},
"dependencies": {
"include-media": "^1.4.9",
"jquery": "^3.3.1",
"normalize.css": "^5.0.0"
}
}
Gulpfile:
(() => {
'use strict';
const cfg = require('./gulp-config.js'),
gulp = require('gulp'),
del = require('del'),
path = require('path'),
notifier = require('node-notifier'),
gutil = require('gulp-util'),
browserSync = require('browser-sync').create();
/**
* Require gulp task from file
* #param {string} taskName Task name
* #param {String} path Path to task file
* #param {Object} options Options for task
* #param {Array} dependencies Task dependencies
*/
function requireTask(taskName, path, options, dependencies) {
let settings = options || {};
const taskFunction = function (callback) {
if (settings.checkProduction) {
settings.isProduction = process.argv[process.argv.length - 1] === 'build';
}
let task = require(path + taskName + '.js').call(this, settings);
return task(callback);
};
settings.taskName = taskName;
if (!Array.isArray(dependencies)) {
gulp.task(taskName, taskFunction);
} else if (dependencies.length === 1) {
gulp.task(taskName, gulp.series(dependencies[0], taskFunction));
} else {
gulp.task(taskName, gulp.series(dependencies, taskFunction));
}
}
/**
* Remove image(s) from build folder if corresponding
* images were deleted from source folder
* #param {Object} event Event object
* #param {String} src Name of the source folder
* #param {String} dest Name of the destination folder
*/
function deleteFile(file, src, dest) {
let fileName = file.path.toString().split('/').pop();
let fileEventWord = file.event == 'unlink' ? 'deleted' : file.event;
let filePathFromSrc = path.relative(path.resolve(src), file.path);
let destFilePath = path.resolve(dest, filePathFromSrc);
try {
del.sync(destFilePath);
console.log(` \u{1b}[32m${fileEventWord}: ${fileName}\u{1b}[0m`);
} catch (error) {
console.log(` \u{1b}[31mFile has already deleted\u{1b}[0m`);
}
}
/**
* Show error in console
* #param {String} prefix Title of the error
* #param {String} err Error message
*/
function showError(prefix, err) {
gutil.log(gutil.colors.white.bgRed(' ' + prefix + ' '), gutil.colors.white.bgBlue(' ' + err.message + ' '));
notifier.notify({
title: prefix,
message: err.message
});
this.emit('end');
}
/**
* template HTML
*/
requireTask(`${cfg.task.fileInclude}`, `./${cfg.folder.tasks}/`, {
templates: cfg.fileInclude.templates,
dest: cfg.fileInclude.dest
});
/**
* Hint HTML
*/
requireTask(`${cfg.task.htmlHint}`, `./${cfg.folder.tasks}/`);
/**
* Lint ES
*/
requireTask(`${cfg.task.esLint}`, `./${cfg.folder.tasks}/`, {
src: cfg.folder.src
});
/**
* Build custom js
*/
requireTask(`${cfg.task.buildCustomJs}`, `./${cfg.folder.tasks}/`, {
src: cfg.folder.src,
dest: cfg.folder.build,
mainJs: cfg.file.mainJs,
checkProduction: true,
showError: showError
});
/**
* Build js vendor (concatenate vendors array)
*/
requireTask(`${cfg.task.buildJsVendors}`, `./${cfg.folder.tasks}/`, {
src: cfg.folder.src,
dest: cfg.folder.build,
vendorJs: cfg.file.vendorJs,
vendorJsMin: cfg.file.vendorJsMin
});
/**
* Build styles for application from SASS
*/
requireTask(`${cfg.task.buildSass}`, `./${cfg.folder.tasks}/`, {
src: cfg.folder.src,
dest: cfg.folder.build,
mainScss: cfg.file.mainScss,
mainScssMin: cfg.file.mainScssMin,
versions: cfg.autoprefixer.versions,
checkProduction: true,
showError: showError
});
/**
* Compile scss files listed in the config
*/
requireTask(`${cfg.task.buildSassFiles}`, `./${cfg.folder.tasks}/`, {
sassFilesInfo: cfg.getPathesForSassCompiling(),
dest: cfg.folder.build,
versions: cfg.autoprefixer.versions,
showError: showError
});
/**
* Build styles for vendor from SASS
*/
requireTask(`${cfg.task.buildStylesVendors}`, `./${cfg.folder.tasks}/`, {
src: cfg.folder.src,
dest: cfg.folder.build,
vendorScss: cfg.file.vendorScss,
vendorScssMin: cfg.file.vendorScssMin,
showError: showError
});
/**
* Minify images
*/
requireTask(`${cfg.task.imageMin}`, `./${cfg.folder.tasks}/`, {
src: cfg.folder.src,
dest: cfg.folder.build
});
/**
* Clean build folder
*/
requireTask(`${cfg.task.cleanBuild}`, `./${cfg.folder.tasks}/`, {
src: cfg.folder.build
});
/**
* Clean production folder
*/
requireTask(`${cfg.task.cleanProd}`, `./${cfg.folder.tasks}/`, {
src: cfg.folder.prod
});
/**
* Copy folders to the build folder
*/
requireTask(`${cfg.task.copyFolders}`, `./${cfg.folder.tasks}/`, {
dest: cfg.folder.build,
foldersToCopy: cfg.getPathesToCopy()
});
/**
* Copy folders to the production folder
*/
requireTask(`${cfg.task.copyFoldersProduction}`, `./${cfg.folder.tasks}/`, {
dest: cfg.folder.prod,
foldersToCopy: cfg.getPathesToCopyForProduction()
});
/**
* Start browserSync server
*/
requireTask(`${cfg.task.browserSync}`, `./${cfg.folder.tasks}/`, {
mainHtml: cfg.file.mainHtml,
browserSync: browserSync
});
/**
* Watch for file changes
*/
requireTask(`${cfg.task.watch}`, `./${cfg.folder.tasks}/`, {
sassFilesInfo: cfg.getPathesForSassCompiling(),
src: cfg.folder.src,
templates: cfg.folder.templates,
dest: cfg.folder.build,
imageExtensions: cfg.imageExtensions,
browserSync: browserSync,
deleteFile: deleteFile,
tasks: {
buildSassFiles: cfg.task.buildSassFiles,
buildCustomJs: cfg.task.buildCustomJs,
buildSass: cfg.task.buildSass,
esLint: cfg.task.esLint,
fileInclude: cfg.task.fileInclude,
htmlHint: cfg.task.htmlHint,
imageMin: cfg.task.imageMin
}
}, false);
/**
* Default Gulp task
*/
gulp.task('default', gulp.series(
cfg.task.cleanBuild,
gulp.parallel(
cfg.task.buildCustomJs,
cfg.task.buildJsVendors,
cfg.task.buildSass,
cfg.task.buildSassFiles,
cfg.task.buildStylesVendors,
cfg.task.fileInclude,
cfg.task.htmlHint,
cfg.task.esLint,
cfg.task.imageMin
),
cfg.task.copyFolders,
gulp.parallel(
cfg.task.browserSync,
cfg.task.watch
)
));
/**
* Creating production folder without unnecessary files
*/
gulp.task('build', gulp.series(
gulp.parallel(
cfg.task.cleanProd,
cfg.task.cleanBuild
),
gulp.parallel(
cfg.task.buildCustomJs,
cfg.task.buildJsVendors,
cfg.task.buildSass,
cfg.task.buildSassFiles,
cfg.task.buildStylesVendors,
cfg.task.fileInclude,
cfg.task.htmlHint,
cfg.task.esLint,
cfg.task.imageMin
),
cfg.task.copyFolders,
cfg.task.copyFoldersProduction
), true);
})();
It's got some issue with Timeout with the binding of the port.
I've added "preinstall": "npm install -g gulp" and
My Procfile shows the following as well:
web: gulp
Can someone help me why it's failing? I really want to deploy this project on Heroku and would very much appreciate any help to solve!
There is no way on the project to bind the port.
Using process.env.PORT || 8080 instead of just 8080 solved my issue. Heroku likes it this way!
I'm using gulp to watch file changes and compile my scss, But watch isn't tracking the file changes.
im using gulp-sass and the version is 4.0
const { src, dest, watch, series } = require('gulp');
const { sass } = require('gulp-sass');
function compileSass() {
return src('app/assets/scss/main.scss')
.pipe(sass())
.pipe(dest('app/css'));
}
function start() {
//compile and watch
watch('app/assets/scss/**/*.scss', { events: 'change' }, function(compileSass) {
// body omitted
compileSass();
});
}
exports.default = series(start);
Try:
function start() {
//compile and watch
watch('app/assets/scss/**/*.scss', { events: 'change' }, function(cb) {
// body omitted
compileSass();
cb();
})
}
cb is a callback function - just leave it as cb (it doesn't need to exist anywhere else) and is called last in the task.
Not sure why your task is not wrapped in gulp.task.
Try to paste this code in your gulpfile.js
gulpfile.js
const gulp = require('gulp');
const sass = require('gulp-sass'); // not { sass }
/** Transpile sass/scss to css */
gulp.task('compile-sass', () => {
return gulp.src('app/assets/scss/main.scss')
.pipe(sass())
.pipe(gulp.dest('app/css'));
});
/** Run the compile-sass task then set a watchers to app/assets/scss/**/*.scss */
gulp.task('watch', gulp.series(
'compile-sass',
(done) => {
gulp.watch('app/assets/scss/**/*.scss')
.on('change', gulp.series('compile-sass'))
done()
},
));
/** Default task */
gulp.task('default', gulp.series('watch'));
Now you can run it using gulp in your terminal.
Hello!
I´m making gulpfile.js and I have this issius:
gulp-notify doesn´t send notification to notification center
gulp-clean-css show efficencie in %/100
Here is my gulpfile.js:
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Gulpfile
========
Impletation:
1. Styles
1.1 Sass to CSS (error catching)
1.2 SourceMaps
1.3 Autoprefixing
1.4 Minify and rename
2. JavaScripts
2.3 Control witch JSHint
2.1 Put it to one file
2.2 Minify and rename
3. Images
3.1 Minify images (.PNG .JPG .JPEG .GIF and .SVG)
3.2 Move
4. Watch and sync
4.1 Watching files
4.2 Reaload browsers
5. Build
5.1 Export files to dist folder (only outputs)
Conent:
-------
1. Project Variables
2. Load plugins
3. Browser Sync Setup
4. Style Task
5. JavaScript Task
6. Images Task
7. Watch Task
8. Build Task
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*==============================
1. Project Variables
==============================*/
/*
Main
*/
var projectNAME = 'StartPlate'
var projectURL = 'startplate.dev/dev';
/*
Styles
*/
var styleSRC = 'dev/sass/**/*.scss';
var styleDEST = 'dev/css';
var minifySRC = ['dev/css/**/*.css', '!dev/css/**/*min.css']
const AUTOPREFIXER_BROWSERS = [
'last 2 version',
'> 1%',
'ie >= 9',
'ie_mob >= 10',
'ff >= 30',
'chrome >= 34',
'safari >= 7',
'opera >= 23',
'ios >= 7',
'android >= 4',
'bb >= 10'
];
/*
JavaScripts
*/
var jsSRC = ['dev/js/**/*.js', '!dev/js/**/*min.js'];
var jsDEST = 'dev/js';
/*
Images
*/
var imagesSRC = 'dev/img/raw/**/*.{png,jpg,jpeg,gif,svg}';
var imagesDEST = 'dev/img';
/*
Wach
*/
var minifyWATCH = 'dev/css/**/*css';
var anotherWATCH = 'dev/**/*.{php,html}';
/*
Build
*/
var buildDEST = 'dist/'; // Files that you want to package into a zip go here
var buildSRC = [
// include common file types
anotherWATCH,
'dev/**/*min.css',
'dev/**/*min.js',
'dev/**/*.svg',
'dev/**/*.png',
'dev/**/*.jpg',
'dev/**/*.jpeg',
'dev/**/*.gif',
'dev/**/*.ttf',
'dev/**/*.otf',
'dev/**/*.eot',
'dev/**/*.woff',
'dev/**/*.woff2',
// include specific files and folders
'dev/robots.txt',
'dev/humans.txt',
// exclude files and folders
'!dev/img/raw/*',
'!dev/**/*.scss',
'!dev/**/*.map'
];
/*==============================
2. Loading Plugins
==============================*/
var gulp = require('gulp');
var rename = require('gulp-rename')
var notify = require('gulp-notify')
var browserSync = require('browser-sync').create();
var reload = browserSync.reload;
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var autoprefixer = require('gulp-autoprefixer');
var cleanCSS = require ('gulp-clean-css');
var concat = require ('gulp-concat');
var jshint = require ('gulp-jshint');
var uglify = require('gulp-uglify');
var imagemin = require ('gulp-imagemin')
/*==============================
3. Browser Synch Setup
==============================*/
gulp.task( 'browser-synch', function() {
browserSync.init( {
// For more options
// #link http://www.browsersync.io/docs/options/
// Project URL.
proxy: projectURL,
// `true` Automatically open the browser with BrowserSync live server.
// `false` Stop the browser from automatically opening.
open: true,
// Inject CSS changes.
// Commnet it to reload browser for every CSS change.
injectChanges: true,
// Use a specific port (instead of the one auto-detected by Browsersync).
// port: 7000,
} );
});
/*==============================
4. Styles Task
==============================*/
gulp.task('style', function () {
return gulp.src( styleSRC )
.pipe(sourcemaps.init())
.pipe(sass({
outputStyle: 'compact'
// outputStyle: 'compressed'
// outputStyle: 'nested'
// outputStyle: 'expanded'
}).on('error', sass.logError))
.pipe( sourcemaps.init( { loadMaps: true } ) )
.pipe( autoprefixer( AUTOPREFIXER_BROWSERS ) )
.pipe(sourcemaps.write('/maps'))
.pipe(gulp.dest( styleDEST ))
.pipe( browserSync.stream() )
.pipe( notify( { message: 'TASK: "style" Completed! 💯', onLast: true } ) );
});
gulp.task('minify', function () {
return gulp.src( minifySRC)
.pipe(cleanCSS({
level: '2',
debug: true}, function(details) {
console.log(details.name + ': old ' + details.stats.originalSize + ' kb');
console.log(details.name + ': new ' + details.stats.minifiedSize + ' kb');
console.log(details.name + ': ' + details.stats.timeSpent + ' ms');
console.log(details.name + ': ' + details.stats.efficiency + '%');
}))
.pipe( rename( { suffix: '.min' } ) )
.pipe(gulp.dest( styleDEST ))
.pipe( browserSync.stream() ) // refresh
.pipe( notify( { message: 'TASK: "minify" Completed! 💯', onLast: true } ) );
});
/*==============================
5. JavaScripts Task
==============================*/
gulp.task('scripts', function() {
return gulp.src( jsSRC)
.pipe(jshint())
.pipe(jshint.reporter('default'))
.pipe(sourcemaps.init())
.pipe(concat('all.js'))
.pipe(rename('index.js'))
.pipe( uglify() )
.pipe( rename( { suffix: '.min' } ) )
.pipe(sourcemaps.write('/maps'))
.pipe(gulp.dest(jsDEST))
.pipe( browserSync.stream() )
.pipe( notify( { message: 'TASK: "scripts" Completed! 💯', onLast: true } ) );
});
/*==============================
6. Images Task
==============================*/
gulp.task( 'images', function() {
gulp.src( imagesSRC )
.pipe( imagemin( {
progressive: true,
optimizationLevel: 7, // 0-7 low-high
interlaced: true,
svgoPlugins: [{removeViewBox: false}]
} ) )
.pipe(gulp.dest( imagesDEST ))
.pipe( browserSync.stream() )
.pipe( notify( { message: 'TASK: "images" Completed! 💯', onLast: true } ) );
});
/*==============================
7. Watch Task
==============================*/
gulp.task( 'default', ['style', 'minify', 'scripts', 'images', 'browser-synch'], function () {
gulp.watch( anotherWATCH, reload);
gulp.watch( styleSRC, [ 'style'] );
gulp.watch( minifySRC, [ 'minify'] );
gulp.watch( jsSRC, [ 'scripts'] );
gulp.watch( imagesSRC, [ 'images'] );
});
/*==============================
8. Build Task
==============================*/
gulp.task('build', function() {
return gulp.src( buildSRC )
.pipe(gulp.dest( buildDEST ))
.pipe( notify( { message: 'TASK: "build" Completed! 💯', onLast: true } ) );
});
I try update npm & all dependencies and it doesn´t help.
toast.exe has allowed notification and in another project it works.
Thanks for any help!
I have the following in my gulpfile.js:
var sass_paths = [
'./httpdocs-site1/media/sass/**/*.scss',
'./httpdocs-site2/media/sass/**/*.scss',
'./httpdocs-site3/media/sass/**/*.scss'
];
gulp.task('sass', function() {
return gulp.src(sass_paths)
.pipe(sass({errLogToConsole: true}))
.pipe(autoprefixer('last 4 version'))
.pipe(minifyCSS({keepBreaks:true}))
.pipe(rename({ suffix: '.min'}))
.pipe(gulp.dest(???));
});
I'm wanting to output my minified css files to the following paths:
./httpdocs-site1/media/css
./httpdocs-site2/media/css
./httpdocs-site3/media/css
Am I misunderstanding how to use sources/destinations? Or am I trying to accomplish too much in a single task?
Edit: Updated output paths to corresponding site directories.
I guess that the running tasks per folder recipe may help.
Update
Following the ideas in the recipe, and oversimplifying your sample just to give the idea, this can be a solution:
var gulp = require('gulp'),
path = require('path'),
merge = require('merge-stream');
var folders = ['httpdocs-site1', 'httpdocs-site2', 'httpdocs-site3'];
gulp.task('default', function(){
var tasks = folders.map(function(element){
return gulp.src(element + '/media/sass/**/*.scss', {base: element + '/media/sass'})
// ... other steps ...
.pipe(gulp.dest(element + '/media/css'));
});
return merge(tasks);
});
you are going to want to use merge streams if you would like to use multiple srcs but you can have multiple destinations inside of the same one. Here is an example.
var merge = require('merge-stream');
gulp.task('sass', function() {
var firstPath = gulp.src(sass_paths[0])
.pipe(sass({errLogToConsole: true}))
.pipe(autoprefixer('last 4 version'))
.pipe(minifyCSS({keepBreaks:true}))
.pipe(rename({ suffix: '.min'}))
.pipe(gulp.dest('./httpdocs-site1/media/css'))
.pipe(gulp.dest('./httpdocs-site2/media/css'));
var secondPath = gulp.src(sass_paths[1])
.pipe(sass({errLogToConsole: true}))
.pipe(autoprefixer('last 4 version'))
.pipe(minifyCSS({keepBreaks:true}))
.pipe(rename({ suffix: '.min'}))
.pipe(gulp.dest('./httpdocs-site1/media/css'))
.pipe(gulp.dest('./httpdocs-site2/media/css'));
return merge(firstPath, secondPath);
});
I assumed you wanted different paths piped here so there is site1 and site2, but you can do this to as many places as needed. Also you can specify a dest prior to any of the steps if, for example, you wanted to have one dest that had the .min file and one that didn't.
You can use gulp-rename to modify where files will be written.
gulp.task('sass', function() {
return gulp.src(sass_paths, { base: '.' })
.pipe(sass({errLogToConsole: true}))
.pipe(autoprefixer('last 4 version'))
.pipe(minifyCSS({keepBreaks:true}))
.pipe(rename(function(path) {
path.dirname = path.dirname.replace('/sass', '/css');
path.extname = '.min.css';
}))
.pipe(gulp.dest('.'));
});
Important bit: use base option in gulp.src.
For the ones that ask themselves how can they deal with common/specifics css files (works the same for scripts), here is a possible output to tackle this problem :
var gulp = require('gulp');
var concat = require('gulp-concat');
var css = require('gulp-clean-css');
var sheets = [
{ src : 'public/css/home/*', name : 'home.min', dest : 'public/css/compressed' },
{ src : 'public/css/about/*', name : 'about.min', dest : 'public/css/compressed' }
];
var common = {
'materialize' : 'public/assets/materialize/css/materialize.css'
};
gulp.task('css', function() {
sheets.map(function(file) {
return gulp.src([
common.materialize,
file.src + '.css',
file.src + '.scss',
file.src + '.less'
])
.pipe( concat(file.name + '.css') )
.pipe( css() )
.pipe( gulp.dest(file.dest) )
});
});
All you have to do now is to add your sheets as the object notation is constructed.
If you have additionnal commons scripts, you can map them by name on the object common, then add them after materialize for this example, but before the file.src + '.css' as you may want to override the common files with your customs files.
Note that in the src attribute you can also put path like this :
'public/css/**/*.css'
to scope an entire descendence.
I had success without needing anything extra, a solution very similar to Anwar Nairi's
const p = {
dashboard: {
css: {
orig: ['public/dashboard/scss/style.scss', 'public/dashboard/styles/*.css'],
dest: 'public/dashboard/css/',
},
},
public: {
css: {
orig: ['public/styles/custom.scss', 'public/styles/*.css'],
dest: 'public/css/',
},
js: {
orig: ['public/javascript/*.js'],
dest: 'public/js/',
},
},
};
gulp.task('default', function(done) {
Object.keys(p).forEach(val => {
// 'val' will go two rounds, as 'dashboard' and as 'public'
return gulp
.src(p[val].css.orig)
.pipe(sourcemaps.init())
.pipe(sass())
.pipe(autoPrefixer())
.pipe(cssComb())
.pipe(cmq({ log: true }))
.pipe(concat('main.css'))
.pipe(cleanCss())
.pipe(sourcemaps.write())
.pipe(gulp.dest(p[val].css.dest))
.pipe(reload({ stream: true }));
});
done(); // <-- to avoid async problems using gulp 4
});
Multiple sources with multiple destinations on gulp without using any extra plugins just doing concatenation on each js and css. Below code works for me. Please try it out.
const gulp = require('gulp');
const concat = require('gulp-concat');
function task(done) {
var theme = {
minifiedCss: {
common: {
src : ['./app/css/**/*.min.css', '!./app/css/semantic.min.css'],
name : 'minified-bundle.css',
dest : './web/bundles/css/'
}
},
themeCss:{
common: {
src : ['./app/css/style.css', './app/css/responsive.css'],
name : 'theme-bundle.css',
dest : './web/bundles/css/'
}
},
themeJs: {
common: {
src: ['./app/js/jquery-2.1.1.js', './app/js/bootstrap.js'],
name: 'theme-bundle.js',
dest: './web/_themes/js/'
}
}
}
Object.keys(theme).map(function(key, index) {
return gulp.src(theme[key].common.src)
.pipe( concat(theme[key].common.name) )
.pipe(gulp.dest(theme[key].common.dest));
});
done();
}
exports.task = task;
Using gulp-if helps me a lot.
The gulp-if first argument. is the gulp-match second argument condition
gulp-if can be found in gulp-if
import {task, src, dest} from 'gulp';
import VinylFile = require("vinyl");
const gulpif = require('gulp-if');
src(['foo/*/**/*.md', 'bar/*.md'])
.pipe(gulpif((file: VinylFile) => /foo\/$/.test(file.base), dest('dist/docs/overview')))
.pipe(gulpif((file: VinylFile) => /bar\/$/.test(file.base), dest('dist/docs/guides')))
});
I think we should create 1 temporary folder for containing all these files. Then gulp.src point to this folder
The destination will have the same directory structure as the source.