What is a good way to integrate express into gulp? - javascript

I've been given a project with existing gulp configuration. I'm completely new to gulp so I don't really understand the code at all. To complete the project I need to use express with ejs instead of the default html. However, I couldn't integrate express into the gulp config file, when I tried gulp-express, the server ended up not working as intended or not working at all (when I replace html with ejs).
I need to know which package should I use for this? What kind of folder structure is good enough? And how could I make express with ejs as the template engine work with gulp? Thank you in advance.
(Sorry if I ask too many questions)
The initial folder structure
The gulp config code
// generated on 2016-05-09 using generator-webapp 2.0.0
import gulp from 'gulp';
import gulpLoadPlugins from 'gulp-load-plugins';
import browserSync from 'browser-sync';
import del from 'del';
import {stream as wiredep} from 'wiredep';
const $ = gulpLoadPlugins();
const reload = browserSync.reload;
gulp.task('styles', () => {
return gulp.src('app/styles/*.scss')
.pipe($.plumber())
.pipe($.sourcemaps.init())
.pipe($.sass.sync({
outputStyle: 'expanded',
precision: 10,
includePaths: ['.']
}).on('error', $.sass.logError))
.pipe($.autoprefixer({browsers: ['> 1%', 'last 2 versions', 'Firefox ESR']}))
.pipe($.sourcemaps.write())
.pipe(gulp.dest('.tmp/styles'))
.pipe(reload({stream: true}));
});
gulp.task('scripts', () => {
return gulp.src('app/scripts/**/*.js')
.pipe($.plumber())
.pipe($.sourcemaps.init())
.pipe($.babel())
.pipe($.sourcemaps.write('.'))
.pipe(gulp.dest('.tmp/scripts'))
.pipe(reload({stream: true}));
});
function lint(files, options) {
return () => {
return gulp.src(files)
.pipe(reload({stream: true, once: true}))
.pipe($.eslint(options))
.pipe($.eslint.format())
.pipe($.if(!browserSync.active, $.eslint.failAfterError()));
};
}
const testLintOptions = {
env: {
mocha: true
}
};
gulp.task('lint', lint('app/scripts/**/*.js'));
gulp.task('lint:test', lint('test/spec/**/*.js', testLintOptions));
gulp.task('html', ['styles', 'scripts'], () => {
return gulp.src('app/*.html')
.pipe($.useref({searchPath: ['.tmp', 'app', '.']}))
.pipe($.if('*.js', $.uglify()))
.pipe($.if('*.css', $.cssnano()))
.pipe($.if('*.html', $.htmlmin({collapseWhitespace: true})))
.pipe(gulp.dest('dist'));
});
gulp.task('images', () => {
return gulp.src('app/images/**/*')
.pipe($.cache($.imagemin({
progressive: true,
interlaced: true,
// don't remove IDs from SVGs, they are often used
// as hooks for embedding and styling
svgoPlugins: [{cleanupIDs: false}]
})))
.pipe(gulp.dest('dist/images'));
});
gulp.task('fonts', () => {
return gulp.src(require('main-bower-files')('**/*.{eot,svg,ttf,woff,woff2}', function (err) {})
.concat('app/fonts/**/*'))
.pipe(gulp.dest('.tmp/fonts'))
.pipe(gulp.dest('dist/fonts'));
});
gulp.task('extras', () => {
return gulp.src([
'app/*.*',
'!app/*.html'
], {
dot: true
}).pipe(gulp.dest('dist'));
});
gulp.task('clean', del.bind(null, ['.tmp', 'dist']));
gulp.task('serve', ['styles', 'scripts', 'fonts'], () => {
browserSync({
notify: false,
port: 9000,
server: {
baseDir: ['.tmp', 'app'],
routes: {
'/bower_components': 'bower_components'
}
}
});
gulp.watch([
'app/*.html',
'app/images/**/*',
'.tmp/fonts/**/*'
]).on('change', reload);
gulp.watch('app/styles/**/*.scss', ['styles']);
gulp.watch('app/scripts/**/*.js', ['scripts']);
gulp.watch('app/fonts/**/*', ['fonts']);
gulp.watch('bower.json', ['wiredep', 'fonts']);
});
gulp.task('serve:dist', () => {
browserSync({
notify: false,
port: 9000,
server: {
baseDir: ['dist']
}
});
});
gulp.task('serve:test', ['scripts'], () => {
browserSync({
notify: false,
port: 9000,
ui: false,
server: {
baseDir: 'test',
routes: {
'/scripts': '.tmp/scripts',
'/bower_components': 'bower_components'
}
}
});
gulp.watch('app/scripts/**/*.js', ['scripts']);
gulp.watch('test/spec/**/*.js').on('change', reload);
gulp.watch('test/spec/**/*.js', ['lint:test']);
});
// inject bower components
gulp.task('wiredep', () => {
gulp.src('app/styles/*.scss')
.pipe(wiredep({
ignorePath: /^(\.\.\/)+/
}))
.pipe(gulp.dest('app/styles'));
gulp.src('app/*.html')
.pipe(wiredep({
exclude: ['bootstrap-sass'],
ignorePath: /^(\.\.\/)*\.\./
}))
.pipe(gulp.dest('app'));
});
gulp.task('build', ['lint', 'html', 'images', 'fonts', 'extras'], () => {
return gulp.src('dist/**/*').pipe($.size({title: 'build', gzip: true}));
});
gulp.task('default', ['clean'], () => {
gulp.start('build');
});

Related

Problems with the gulp watch

I am preparing a project, and decided to use the gulp collector. I wrote commands, but gulp watch does not work. It does not produce any errors in the terminal at startup, because of this it is difficult to understand what the problem is. Maybe someone came across a similar one.
I enclose the code in gulpfile.js
'use strict';
var gulp = require('gulp'),
watch = require('gulp-watch'),
prefixer = require('gulp-autoprefixer'),
uglify = require('gulp-uglify'),
sass = require('gulp-sass'),
sourcemaps = require('gulp-sourcemaps'),
rigger = require('gulp-rigger'),
cssmin = require('gulp-minify-css'),
imagemin = require('gulp-imagemin'),
pngquant = require('imagemin-pngquant'),
rimraf = require('rimraf'),
browserSync = require("browser-sync"),
reload = browserSync.reload;
var path = {
build: {
html: 'build/',
js: 'build/js/',
css: 'build/css/',
img: 'build/img/',
fonts: 'build/fonts/'
},
src: {
html: 'src/*.html',
js: 'src/js/**/*.js',
style: 'src/style/**/*.scss',
img: 'src/img/**/*.*',
fonts: 'src/fonts/**/*.*'
},
watch: {
html: 'src/**/*.html',
js: 'src/js/**/*.js',
style: 'src/style/**/*.scss',
img: 'src/img/**/*.*',
fonts: 'src/fonts/**/*.*'
},
clean: './build'
};
var config = {
server: {
baseDir: "./build"
},
tunnel: false, /* Создание временного тунеля заблокированно */
host: 'localhost',
port: 9000,
logPrefix: "Eugene Kobeliaksky"
};
gulp.task('webserver', function (done) {
browserSync(config);
done();
});
gulp.task('clean', function (cb) {
rimraf(path.clean, cb);
});
gulp.task('html:build', function () {
gulp.src(path.src.html)
.pipe(rigger())
.pipe(gulp.dest(path.build.html))
.pipe(reload({stream: true}));
});
gulp.task('js:build', function () {
gulp.src(path.src.js)
.pipe(rigger())
.pipe(sourcemaps.init())
.pipe(uglify())
.pipe(sourcemaps.write())
.pipe(gulp.dest(path.build.js))
.pipe(browserSync.reload({stream: true}));//edit live reload
});
gulp.task('style:build', function () {
gulp.src(path.src.style)
.pipe(sourcemaps.init())
.pipe(sass({
sourceMap: true,
errLogToConsole: true
}))
.pipe(prefixer())
.pipe(cssmin())
.pipe(sourcemaps.write())
.pipe(gulp.dest(path.build.css))
.pipe(reload({stream: true}));
});
gulp.task('image:build', function () {
gulp.src(path.src.img)
.pipe(imagemin({
progressive: true,
svgoPlugins: [{removeViewBox: false}],
use: [pngquant()],
interlaced: true
}))
.pipe(gulp.dest(path.build.img))
.pipe(reload({stream: true}));
});
gulp.task('fonts:build', function() {
gulp.src(path.src.fonts)
.pipe(gulp.dest(path.build.fonts))
});
gulp.task('build', [
'html:build',
'js:build',
'style:build',
'fonts:build',
'image:build'
]);
gulp.task('watch', function(){
watch([path.watch.html], function(event, cb, done) {
gulp.start('html:build');
done();
});
watch([path.watch.style], function(event, cb, done) {
gulp.start('style:build');
done();
});
watch([path.watch.js], function(event, cb, done) {
gulp.start('js:build');
done();
});
watch([path.watch.img], function(event, cb, done) {
gulp.start('image:build');
done();
});
watch([path.watch.fonts], function(event, cb, done) {
gulp.start('fonts:build');
done();
});
});
gulp.task('default', ['build', 'webserver', 'watch']);

Gulp build task CSS paths and JS compilation

So I have the following basic project structure that I use throughout all my projects:
Where the src folder looks like this:
I use Pug(Jade), sass compiling and useref js compilation.
This is my Jade views structure:
And this is my Jade index file:
This is my Jade scripts file, that is included in the index:
This is my pre-build index file, which is constructed by the index.pug:
And this is the build version of the index file:
My Gulpfile looks like this:
var gulp = require('gulp'),
sass = require('gulp-sass'),
plumber = require('gulp-plumber'),
changed = require('gulp-changed'),
gutil = require('gulp-util'),
pug = require('gulp-pug'),
concat = require('gulp-concat'),
browserSync = require('browser-sync').create(),
useref = require('gulp-useref'),
uglify = require('gulp-uglify'),
gulpIf = require('gulp-if'),
cssnano = require('gulp-cssnano'),
imagemin = require('gulp-imagemin'),
cache = require('gulp-cache'),
del = require('del'),
cssAdjustUrlPath = require('gulp-css-adjust-url-path'),
runSequence = require('run-sequence');
function handleError(err) {
gutil.beep();
console.log(err.toString());
this.emit('end');
}
gulp.task('sass', function () {
return gulp.src('src/scss/**/*.scss')
.pipe(plumber({
errorHandler: handleError
}))
.pipe(sass()) // Using gulp-sass
.pipe(gulp.dest('src/css'))
.pipe(browserSync.reload({
stream: true
}));
});
gulp.task('sass-dist', function () {
return gulp.src('src/scss/**/*.scss')
.pipe(cssAdjustUrlPath(/(url\(['"]?)[/]?(assets)/g))
.pipe(sass()) // Using gulp-sass
.pipe(gulp.dest('dist/css'))
});
gulp.task('views', function buildHTML() {
return gulp.src('src/views/*.pug')
.pipe(changed('src', {
extension: '.html'
}))
.pipe(pug({
pretty: true
}))
.pipe(gulp.dest('src/'))
});
gulp.task('views-dist', function buildHTML() {
return gulp.src('src/views/*.pug')
.pipe(changed('src', {
extension: '.html'
}))
.pipe(pug({
pretty: true
}))
.pipe(gulp.dest('dist/'))
});
gulp.task('watch', ['browserSync', 'views', 'sass'], function () {
gulp.watch('src/scss/**/*.scss', ['sass']);
gulp.watch('src/views/**/*.pug', ['views']);
// Reloads the browser whenever HTML or JS files change
gulp.watch('src/js/**/*.js', browserSync.reload);
gulp.watch('src/*.html', browserSync.reload);
});
gulp.task('browserSync', function () {
browserSync.init({
server: {
baseDir: 'src'
},
port: 3000
});
});
gulp.task('useref', function () {
return gulp.src('src/*.html')
.pipe(useref())
.pipe(gulpIf('*.js', uglify()))
// Minifies only if it's a CSS file
.pipe(gulpIf('*.css', cssnano()))
.pipe(gulp.dest('dist'));
});
gulp.task('useref-dist', function () {
return gulp.src('src/**/*.html')
.pipe(useref())
.pipe(gulpIf('*.js', uglify()))
// Minifies only if it's a CSS file
.pipe(gulpIf('*.css', cssnano()))
.pipe(gulp.dest('dist'));
});
gulp.task('images', function () {
return gulp.src('src/images/**/*.+(png|jpg|jpeg|gif|svg)')
// Caching images that ran through imagemin
.pipe(cache(imagemin({
interlaced: true
})))
.pipe(gulp.dest('src/images/'));
});
gulp.task('images-dist', function () {
return gulp.src('src/images/**/*.+(png|jpg|jpeg|gif|svg)')
// Caching images that ran through imagemin
.pipe(cache(imagemin({
interlaced: true
})))
.pipe(gulp.dest('dist/images/'));
});
gulp.task('fonts', function () {
return gulp.src('src/fonts/**/*')
.pipe(gulp.dest('dist/fonts'));
});
gulp.task('clean:dist', function () {
return del.sync('dist');
});
gulp.task('build', function (callback) {
runSequence('clean:dist', ['sass-dist', 'useref-dist', 'images-dist', 'fonts', 'views-dist'],
callback
);
});
gulp.task('default', function (callback) {
runSequence(['views', 'sass', 'browserSync', 'watch'],
callback
);
});
When I run the build task gulp build, all is well, except the relative/absolute paths inside the outputted CSS files, and the JS that runs the final product, whereas fonts/backgrounds/icons and JS functionality is not translated into the final build.
What is wrong with my Gulp file, and how can I fix it?

Gulp Browsersync causing multiple reloads with each filechange

I'm using browsersync with Gulp, running some tasks on particular filechanges. Whenever I save a file, I get 10+ [BS] Reloading Browsers... in my terminal and performance is understandably laggy.
Here are my gulpfile:
gulp.task('bowerJS', function() {
gulp.src(lib.ext('js').files)
.pipe(concat('lib.min.js'))
.pipe(uglify())
.pipe(gulp.dest('app/assets/js'));
});
gulp.task('bowerCSS', function() {
gulp.src(lib.ext('css').files)
.pipe(concat('lib.min.css'))
.pipe(gulp.dest('app/assets/css/'));
});
// Compile sass into CSS & auto-inject into browsers
gulp.task('less', function() {
gulp.src('./app/css/*.less')
.pipe(less())
.pipe(autoprefixer({
browsers: ['last 2 versions'],
cascade: false
}))
.pipe(gulp.dest('app/assets/css'))
.pipe(browserSync.stream());
});
// Render Jade templates as HTML files
gulp.task('templates', function() {
gulp.src('views/**/*.jade')
.pipe(jade({
pretty: true
}))
.pipe(gulp.dest('app/src/'))
});
gulp.task('php', function() {
php.server({ base: 'app', port: 8123, keepalive: true});
});
gulp.task('serve', ['bowerJS', 'bowerCSS', 'less', 'templates', 'php'], function() {
var proxyOptions1 = url.parse('http://some-site:1234');
proxyOptions1.route = '/api/hi';
browserSync({
port: 8999,
proxy: '127.0.0.1:8123',
middleware: [
proxy(proxyOptions1),
history()
],
notify: false
});
gulp.watch("app/assets/css/*.less", ['less']);
gulp.watch("app/**/*.html").on('change', browserSync.reload);
gulp.watch("app/assets/js/*.js").on('change', browserSync.reload);
gulp.watch("views/**/*.jade", ['templates']);
});
What am I doing wrong here?
use only browserSync.stream (replace browserSync.reload then) and pass option once: true like this
browserSync.stream({once: true})
this should works fine.
The awaitWriteFinish option in Chokidar fixed it for me.
Example:
browserSync.init({
server: dist.pages,
files: dist.css + '*.css',
watchOptions: {
awaitWriteFinish : true
}
});

What's responsible for creating the filename signature in this Gulp task?

When I run gulp build it creates a file with a name like this:
dist/scripts/app-f3c1dbf348.js
The f3c1dbf348 part is something different every time. Obviously something is making this happen but it's not clear to me what.
Below is my gulp/build.js. What there (if anything there) is generating the f3c1dbf348 part of the filename? I want the filename just to be app.js because my concatenated .js file needs to be included as a Bower component.
'use strict';
var path = require('path');
var gulp = require('gulp');
var conf = require('./conf');
var $ = require('gulp-load-plugins')({
pattern: ['gulp-*', 'main-bower-files', 'uglify-save-license', 'del']
});
gulp.task('partials', function () {
return gulp.src([
path.join(conf.paths.src, '/app/**/*.html'),
path.join(conf.paths.tmp, '/serve/app/**/*.html')
])
.pipe($.minifyHtml({
empty: true,
spare: true,
quotes: true
}))
.pipe($.angularTemplatecache('templateCacheHtml.js', {
module: 'lmsComponents',
root: 'app'
}))
.pipe(gulp.dest(conf.paths.tmp + '/partials/'));
});
gulp.task('html', ['inject', 'partials'], function () {
var partialsInjectFile = gulp.src(path.join(conf.paths.tmp, '/partials/templateCacheHtml.js'), { read: false });
var partialsInjectOptions = {
starttag: '<!-- inject:partials -->',
ignorePath: path.join(conf.paths.tmp, '/partials'),
addRootSlash: false
};
var htmlFilter = $.filter('*.html', { restore: true });
var jsFilter = $.filter('**/*.js', { restore: true });
var cssFilter = $.filter('**/*.css', { restore: true });
var assets;
return gulp.src(path.join(conf.paths.tmp, '/serve/*.html'))
.pipe($.inject(partialsInjectFile, partialsInjectOptions))
.pipe(assets = $.useref.assets())
.pipe($.rev())
.pipe(jsFilter)
.pipe($.sourcemaps.init())
.pipe($.ngAnnotate())
.pipe($.uglify({ preserveComments: $.uglifySaveLicense })).on('error', conf.errorHandler('Uglify'))
.pipe($.sourcemaps.write('maps'))
.pipe(jsFilter.restore)
.pipe(cssFilter)
.pipe($.sourcemaps.init())
.pipe($.replace('../../bower_components/bootstrap-sass/assets/fonts/bootstrap/', '../fonts/'))
.pipe($.minifyCss({ processImport: false }))
.pipe($.sourcemaps.write('maps'))
.pipe(cssFilter.restore)
.pipe(assets.restore())
.pipe($.useref())
.pipe($.revReplace())
.pipe(htmlFilter)
.pipe($.minifyHtml({
empty: true,
spare: true,
quotes: true,
conditionals: true
}))
.pipe(htmlFilter.restore)
.pipe(gulp.dest(path.join(conf.paths.dist, '/')))
.pipe($.size({ title: path.join(conf.paths.dist, '/'), showFiles: true }));
});
// Only applies for fonts from bower dependencies
// Custom fonts are handled by the "other" task
gulp.task('fonts', function () {
return gulp.src($.mainBowerFiles())
.pipe($.filter('**/*.{eot,svg,ttf,woff,woff2}'))
.pipe($.flatten())
.pipe(gulp.dest(path.join(conf.paths.dist, '/fonts/')));
});
gulp.task('other', function () {
var fileFilter = $.filter(function (file) {
return file.stat.isFile();
});
return gulp.src([
path.join(conf.paths.src, '/**/*'),
path.join('!' + conf.paths.src, '/**/*.{html,css,js,scss}')
])
.pipe(fileFilter)
.pipe(gulp.dest(path.join(conf.paths.dist, '/')));
});
gulp.task('clean', function () {
return $.del([path.join(conf.paths.dist, '/'), path.join(conf.paths.tmp, '/')]);
});
gulp.task('build', ['html', 'fonts', 'other']);
It was this line:
.pipe($.rev())

Trying to build to correct directory using gulp

I used yeoman webapp to start my website. The goal is to make it
<script src=./scripts/vendor.js></script>
<script src=./scripts/main.js></script>
For my html files in another folder.
This my gulp file:
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var browserSync = require('browser-sync');
var reload = browserSync.reload;
gulp.task('styles', function () {
return gulp.src('app/styles/main.scss')
.pipe($.sourcemaps.init())
.pipe($.sass({
outputStyle: 'nested', // libsass doesn't support expanded yet
precision: 10,
includePaths: ['.'],
onError: console.error.bind(console, 'Sass error:')
}))
.pipe($.postcss([
require('autoprefixer-core')({browsers: ['last 1 version']})
]))
.pipe($.sourcemaps.write())
.pipe(gulp.dest('.tmp/styles'))
.pipe(reload({stream: true}));
});
gulp.task('jshint', function () {
return gulp.src('app/scripts/**/*.js')
.pipe(reload({stream: true, once: true}))
.pipe($.jshint())
.pipe($.jshint.reporter('jshint-stylish'))
.pipe($.if(!browserSync.active, $.jshint.reporter('fail')));
});
gulp.task('html', ['styles'], function () {
var assets = $.useref.assets({searchPath: ['.tmp', 'app', '.']});
return gulp.src('app/*.html')
.pipe(assets)
.pipe($.if('*.js', $.uglify()))
.pipe($.if('*.css', $.csso()))
.pipe(assets.restore())
.pipe($.useref())
.pipe($.if('*.html', $.minifyHtml({conditionals: true, loose: true})))
.pipe(gulp.dest('dist'));
});
gulp.task('images', function () {
return gulp.src('app/images/**/*')
.pipe($.cache($.imagemin({
progressive: true,
interlaced: true,
// don't remove IDs from SVGs, they are often used
// as hooks for embedding and styling
svgoPlugins: [{cleanupIDs: false}]
})))
.pipe(gulp.dest('dist/images'));
});
gulp.task('fonts', function () {
return gulp.src(require('main-bower-files')({
filter: '**/*.{eot,svg,ttf,woff,woff2}'
}).concat('app/fonts/**/*'))
.pipe(gulp.dest('.tmp/fonts'))
.pipe(gulp.dest('dist/fonts'));
});
gulp.task('extras', function () {
return gulp.src([
'app/*.*',
'!app/*.html',
'app/'+'**/*.html'
], {
dot: true
}).pipe(gulp.dest('dist'));
});
gulp.task('clean', require('del').bind(null, ['.tmp', 'dist']));
gulp.task('serve', ['styles', 'fonts'], function () {
browserSync({
notify: false,
port: 9000,
server: {
baseDir: ['.tmp', 'app'],
routes: {
'/bower_components': 'bower_components'
}
}
});
// watch for changes
gulp.watch([
'app/*.html',
'app/'+'**/*.html',
'app/scripts/**/*.js',
'app/images/**/*',
'.tmp/fonts/**/*'
]).on('change', reload);
gulp.watch('app/styles/**/*.scss', ['styles']);
gulp.watch('app/fonts/**/*', ['fonts']);
gulp.watch('bower.json', ['wiredep', 'fonts']);
});
// inject bower components
gulp.task('wiredep', function () {
var wiredep = require('wiredep').stream;
gulp.src('app/styles/*.scss')
.pipe(wiredep({
ignorePath: /^(\.\.\/)+/
}))
.pipe(gulp.dest('app/styles'));
gulp.src(['app/*.html', 'app/'+'**/*.html'])
.pipe(wiredep({
exclude: ['bootstrap-sass-official'],
ignorePath: /^(\.\.\/)*\.\./
}))
.pipe(gulp.dest('app'));
});
gulp.task('build', ['jshint', 'html', 'images', 'fonts', 'extras'], function () {
return gulp.src('dist/**/*').pipe($.size({title: 'build', gzip: true}));
});
gulp.task('default', ['clean'], function () {
gulp.start('build');
});
I think the problem is somewhere when it tries to uglify. welp!

Categories