gulp-nodemon + browserSync: has no method 'spawnSync' & long loading time - gulp

I want to run nodemon with browsersync, so that I can see changes in my code instantly. I already had a setup environment from yeoman gulp-angular so I want to avoid using liverload etc. and stick to the preset unless there is a huge reason.
I start my server with `gulp:serve'
gulp.task('serve', ['node'], function () {
browserSyncInit([
paths.tmp + '/serve',
paths.src
], [
paths.tmp + '/serve/{app,components}/**/*.css',
paths.tmp + '/serve/{app,components,node,config}/**/*.js',
paths.src + 'src/assets/images/**/*',
paths.tmp + '/serve/*.html',
paths.tmp + '/serve/{app,components}/**/*.html',
paths.src + '/{app,components}/**/*.html'
]);
});
Before browserSync is called the task node is required otherwise the routes would run into nothing:
gulp.task('node',['watch'], function(){
return nodemon({
script: paths.tmp + '/serve/server.js',
ext: 'js html',
tasks: ['browserSync'],
env: { 'NODE_ENV': 'development' } ,
nodeArgs: ['--debug=9999']
});
});
The task node starts gulp-nodemon and trigers watch to build and watch the application.
gulp.task('watch', ['templateCache', 'images_tmp', 'partials_tmp'], function () {
gulp.watch([
paths.src + '/*.html',
paths.src + '/{app,components}/**/*.scss',
paths.src + '/{app,components}/**/*.js',
paths.src + '/{app,components,node,config}/**/*.coffee',
'bower.json'
], ['templateCache', 'partials_tmp']);
});
Watch itself triggers two functions, one which inserts a scriptTag into index.html to load angularTemplateCache. And a second one which takes all html files and saves them into a templateCache.js. The second one reqires a task which copies all css & js files.
Question 1):
When I change files, it throws the error:
gulp-nodemon/index.js:76
cp.spawnSync('gulp', tasks, { stdio: [0, 1, 2] })
^
TypeError: Object #<Object> has no method 'spawnSync'
Question 2):
When I start the function, all works but it loads very long. I can speed up the loading by manually refreshing the tab which broserSync opened.
EDIT 1:
Gulp-nodemon watches the files in the directory for changes so I removed gulp-watch to exclude a source for errors. The spawnSync error stays:
gulp.task('node',['templateCache', 'images_tmp', 'partials_tmp'], function(){
return nodemon({
script: paths.tmp + '/serve/server.js',
ext: 'js html coffee scss',
tasks: ['templateCache', 'partials_tmp'],
env: { 'NODE_ENV': 'development' } ,
nodeArgs: ['--debug=9999']
}).on('restart' , function onRestart() {
console.log("################################restarted node");
//Also reload the browsers after a slight delay
setTimeout(function reload() {
browserSync.reload({
stream: false
});
}, 5000);
});
});
Edit 2:
I could solve the long loading time issue by moving the browsersync init function into the on start event of nodemon. maybe nodemon wasn't fully loaded before.
gulp.task('node',['templateCache', 'images_tmp', 'partials_tmp'], function(cb){
var called = false;
return nodemon({
script: paths.tmp + '/serve/server.js',
ext: 'js html coffee scss',
tasks: ['node'],
env: { 'NODE_ENV': 'development' } ,
nodeArgs: ['--debug=9999']
})
.on('start', function onStart() {
if (!called) {
cb();
browserSyncInit([
paths.tmp + '/serve',
paths.src
], [
paths.tmp + '/serve/{app,components}/**/*.css',
paths.tmp + '/serve/{app,components,node,config}/**/*.js',
paths.src + 'src/assets/images/**/*',
paths.tmp + '/serve/*.html',
paths.tmp + '/serve/{app,components}/**/*.html',
paths.src + '/{app,components}/**/*.html'
]);
}
called = true;
})
.on('restart' , function onRestart() {
console.log("################################restarted node");
//Also reload the browsers after a slight delay
setTimeout(function reload() {
browserSync.reload({
stream: false
});
}, 5000);
});
});

Problem is in your node.js version. In the latest update of gulp-nodemon you can see, that 0.12.x required. So if you installed new version of gulp-nodemon, on lower node.js you'll see that error.
https://github.com/JacksonGariety/gulp-nodemon/releases/tag/2.0.2
You may update node and the second way is to install previous version of gulp-nodemon.
Good luck!

Related

gulp task flow not working as expected

I have two tasks and they are 'styles' and 'clean-styles'. A watch task watches for any changes in .less files and triggers the styles task when it finds a change. This scenario works fine.
When there is a syntax error in .less, the error is shown on cmd line by gulp-plumber and rest of execution stops which is also correct.
Upon correcting the mistake in .less, watch resumes and triggers off styles task, but styles task just completes the dependent clean-styles task and nothing proceeds further.
I also want style task to execute. Please help.
gulp.task('styles', ['clean-styles'], function () {
config.log('Less -> CSS compilation in progress... [gulp-inject, gulp-less, autoprefixer]');
var partialLessfiles = gulp.src(
[
path.join(config.paths.styles, '**/*.less'),
path.join('!' + config.paths.styles, 'index.less')
],
{read: false}
).pipe(print());
return gulp.src([path.join(config.paths.styles, 'index.less')])
.pipe(inject(partialLessfiles, injectOptions))
.pipe(plumber())
.pipe(less())
.pipe(autoprefixer())
.pipe(gulp.dest(config.paths.temp));
});
gulp.task('clean-styles', function() {
config.log('Deleting all styles from .tmp in progress...');
var files = config.paths.temp + '**/*.css';
config.clean(files);
});
config.clean = function(path) {
util.log('Deleting ' + path);
del(path);
};
gulp.task('less-watcher', function() {
config.log('Watching for any changes in .less files... [watch]');
gulp.watch([config.paths.allless], ['styles']);
});

Deploying Angular2 Application - Folder Structure Changes

GitHub Repository
Summary
After changing my folder structure to keep development and production separate I get a Uncaught SyntaxError: Unexpected token < error.
Note
When I upload my production folder contents via FTP, the site works fine. Only when local do I get the above stated error. Before changing the folder structure, my local server (gulp-connect) worked just fine.
Issue
I an encountering the following errors:
Uncaught SyntaxError: Unexpected token <
My application was working great and ready to launch. I had been working locally with a gulp-connect server. I wanted to create a gulp task that would minify code, copy/paste dependencies, compress image. My end goal would be to have a folder that contained only production ready files.
To do this I created the following folder structure:
Folder Structure
The first and biggest change was to copy/paste (using gulp) the node modules dependencies into appropriate folders. As these changed I updated my index.html to reflect to new locations of the scripts from the node_modules folder to /js.
index.html
<!doctype html>
<html lang="en">
<head>
<link rel="icon"
type="image/png"
href="images/HWA_Emblem.png">
<base href="/">
<meta charset="UTF-8">
<title>Halifax Wildlife Association</title>
<link rel="stylesheet" href="css/style.css">
<script src="js/lib/shim.min.js"></script>
<script src="js/lib/Reflect.js"></script>
<script src="js/lib/system.src.js"></script>
<script src="js/lib/zone.js"></script>
<script src="systemjs.config.js"></script>
<script>
System.import('app').catch(function(err){ console.error(err); });
</script>
</head>
<body>
<my-app></my-app>
<script src="js/lib/jquery-3.1.1.min.js"></script>
<script src="js/scripts.js"></script>
<script src="js/lib/format-google-calendar.js"></script>
</body>
</html>
systemjs.config.js
/**
* System configuration for Angular 2 samples
* Adjust as necessary for your application needs.
*/
(function (global) {
// map tells the System loader where to look for things
var map = {
'app': 'app', // 'dist',
'#angular': '/js/lib/#angular',
'ng2-page-scroll': '/js/lib/ng2-page-scroll.umd.js',
'rxjs': '/js/lib/rxjs'
};
// packages tells the System loader how to load when no filename and/or no extension
var packages = {
'app': { main: 'main.js', defaultExtension: 'js' },
'rxjs': { defaultExtension: 'js' }
};
var ngPackageNames = [
'common',
'compiler',
'core',
'forms',
'http',
'platform-browser',
'platform-browser-dynamic',
'router'
];
// Individual files (~300 requests):
function packIndex(pkgName) {
packages['#angular/' + pkgName] = { main: 'index.js', defaultExtension: 'js' };
}
// Bundled (~40 requests):
function packUmd(pkgName) {
packages['#angular/' + pkgName] = { main: '/bundles/' + pkgName + '.umd.js', defaultExtension: 'js' };
}
// Most environments should use UMD; some (Karma) need the individual index files
var setPackageConfig = System.packageWithIndex ? packIndex : packUmd;
// Add package entries for angular packages
ngPackageNames.forEach(setPackageConfig);
var config = {
map: map,
packages: packages
};
System.config(config);
})(this);
config.rb
I use compass to compile my SASS so I then updated this accordingly:
require 'compass/import-once/activate'
require 'breakpoint'
# Require any additional compass plugins here.
# Set this to the root of your project when deployed:
http_path = "/builds/development"
css_dir = 'stylesheets'
sass_dir = 'sass'
images_dir = 'images'
javascripts_dir = 'javascripts'
sass_options = false
#tsconfig.json#
My TSConfig file had no changes
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"removeComments": false,
"noImplicitAny": false
}
}
gulpfile.js
I am not done of this file just yet, it however does correctly make a production folder.
// Add requiements
var gulp = require ('gulp'),
gutil = require ('gulp-util'),
concat = require ('gulp-concat'),
browserify = require ('gulp-browserify'),
compass = require ('gulp-compass'),
connect = require ('gulp-connect');
sourcemaps = require ('gulp-sourcemaps');
typescript = require ('gulp-typescript');
tsConfig = require ('./tsconfig.json');
gulpif = require ('gulp-if');
uglify = require ('gulp-uglify');
var env,
htmlSources,
sassSource,
jsSources,
appSources,
imageSources,
tsSources,
depSources,
outputDir
env = process.env.NODE_ENV || 'development';
if (env==='development') {
outputDir = 'builds/development/';
} else{
outputDir = 'builds/production/';
}
//Setup path variables
htmlSources = [
'builds/development/partials/*.html',
'builds/development/index.html'
];
sassSources = [
'builds/development/components/sass/style.scss'
];
jsSources = [
'builds/development/components/scripts/*.js'
];
depSources = [
'js/lib'
];
tsSrc = [
'builds/development/components/typescript/*.ts'
];
imageSources= [
'builds/development/images/**/*.*'
];
gulp.task('CopyDep', function(){
gulp.src('node_modules/core-js/client/shim.min.js').pipe(gulp.dest(outputDir + depSources));
gulp.src('node_modules/zone.js/dist/zone.js').pipe(gulp.dest(outputDir + depSources));
gulp.src('node_modules/reflect-metadata/Reflect.js').pipe(gulp.dest(outputDir + depSources));
gulp.src('node_modules/systemjs/dist/system.src.js').pipe(gulp.dest(outputDir + depSources));
gulp.src('builds/development/components/scripts/format-google-calendar.js').pipe(gulp.dest(outputDir + depSources));
gulp.src('builds/development/components/scripts/jquery-3.1.1.min.js').pipe(gulp.dest(outputDir + depSources));
gulp.src('builds/development/components/scripts/jquery-3.1.1.min.js').pipe(gulp.dest(outputDir + depSources));
gulp.src('builds/development/systemjs.config.js').pipe(gulpif(env === 'production', gulp.dest(outputDir)))
gulp.src('node_modules/#angular/**/*').pipe(gulp.dest(outputDir + 'js/lib/#angular'));
gulp.src('node_modules/ng2-page-scroll/bundles/ng2-page-scroll.umd.js').pipe(gulp.dest(outputDir + 'js/lib'));
gulp.src('node_modules/rxjs/**/*.*').pipe(gulp.dest(outputDir + 'js/lib/rxjs'));
});
//Combine Javascript Files
gulp.task('js', function(){
gulp.src(jsSources)
.pipe(concat('scripts.js'))
.pipe(browserify())
.pipe(gulp.dest(outputDir + 'js'))
.pipe(connect.reload())
});
//Process Typescript
gulp.task('typescript', function () {
return gulp
.src(tsSrc)
.pipe(sourcemaps.init())
.pipe(typescript(tsConfig.compilerOptions))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest(outputDir + 'app'))
.pipe(connect.reload());
});
//Process SASS files
gulp.task('compass', function(){
gulp.src(sassSources)
.pipe(compass({
config_file: 'config.rb',
css: 'temp',
sass: 'builds/development/components/sass'
}))
.on('error', gutil.log)
.pipe(gulp.dest(outputDir + 'css'))
.pipe(connect.reload())
});
//Reload HTML files if change is recorded.
gulp.task('html', function(){
gulp.src(htmlSources[1])
.pipe(gulpif(env === 'production', gulp.dest(outputDir)))
gulp.src(htmlSources[0])
.pipe(gulpif(env === 'production', gulp.dest(outputDir + 'partials')))
.pipe(connect.reload());
});
// Watch all sources file directorys and run tasks if changes happen.
gulp.task('watch', function(){
gulp.watch(jsSources, ['js']);
gulp.watch(sassSources, ['compass']);
gulp.watch(htmlSources, ['html']);
gulp.watch(tsSrc, ['typescript']);
});
// copy images in production
gulp.task('images', function(){
gulp.src(imageSources)
.pipe(gulpif(env === 'production', gulp.dest(outputDir + 'images')))
});
// Start a server for project.
gulp.task('connect', function(){
connect.server({
root : '',
livereload : true,
fallback: 'builds/development/index.html'
});
});
// Run all tasks above by using default command "Gulp".
gulp.task('default', ['CopyDep', 'images', 'js', 'images', 'typescript', 'compass', 'html', 'watch', 'connect']);

Gulp watch delete files

I'm new to Gulp, i did some research but not found solutions .. Here is my Gulpfile.
var gulp = require('gulp');
var watch = require('gulp-watch');
var imagemin = require('gulp-imagemin');
var browserSync = require('browser-sync').create();
var paths = {
src: 'src/',
dist: 'dist/',
html: '**/*.html',
php: '**/*.php',
images: {
src: 'assets/img/**/*.{png,jpg,jpeg,svg,gif}',
dist: 'assets/img'
},
misc: '**/*.{ico,htaccess,txt}'
}
/**
* Files
*/
gulp.task('files', function(){
return gulp.src([
paths.src + paths.php,
paths.src + paths.html,
paths.src + paths.misc
])
.pipe(gulp.dest(paths.dist))
.pipe(browserSync.stream());
});
/**
* Images
*/
gulp.task('images', function(){
return gulp.src(
paths.src + paths.images.src
)
.pipe(imagemin({
progressive: true
}))
.pipe(gulp.dest(paths.dist + paths.images.dist))
.pipe(browserSync.stream());
});
/**
* Serve
*/
gulp.task('serve', ['files', 'images'], function(){
browserSync.init({
server: {
baseDir: 'dist'
}
});
watch([
paths.src + paths.php,
paths.src + paths.html,
paths.src + paths.misc
], function(){ gulp.start('files') });
watch(
paths.src + paths.images.src
, function(){ gulp.start('images') });
});
All is ok but during watching files from my "src" folder (serve task), when i delete a file (image or html,php etc...) in "src", the file is not deleted in the "dist" folder.
When file changed or added, no problem.. I've found some similar topics but not the solution..
Thanks.
The reason files aren't deleted in your dist folder is because gulp.watch() simply reruns a task whenever a watched file changes. That task doesn't know that the reason it is running is because a file was deleted. It simply processes all files matching the glob in its gulp.src() statement.
Since the deleted file doesn't exist anymore, it is not picked up by gulp.src() and your task doesn't process it. It is simply left standing as it is in your dist folder, while the other files there are overwritten.
One way to fix this is to follow the Handling the Delete Event on Watch recipe:
var fileWatcher = watch([
paths.src + paths.php,
paths.src + paths.html,
paths.src + paths.misc
], function(){ gulp.start('files') });
fileWatcher.on('change', function (event) {
if (event.type === 'deleted') {
var filePathFromSrc = path.relative(path.resolve(paths.src), event.path);
var destFilePath = path.resolve(paths.dist, filePathFromSrc);
del.sync(destFilePath);
}
});
The handling for your images would be analogous.

After 'html' task file index.html still not exists in Gulp

I run simple configuration:
gulp.task('html', function() {
gulp.src(config.paths.html)
.pipe(gulp.dest(config.paths.dist))
.pipe(connect.reload());
});
gulp.task('connect', function() {
server.listen(config.port);
lrserver.listen(config.livereloadport);
});
gulp.task('open', ['connect'], function() {
gulp.src('dist/index.html')
.pipe(open({ uri: config.devBaseUrl + ':' + config.port + '/'}));
});
gulp.task('default', ['html', 'open']);
But, the first time on 'open' task file index.html still not exists and only the second time it is created and task 'open' will execute successful. What's wrong with my configuration?
I've add a console log:
D:\Projects\demo>gulp
[11:01:13] Using gulpfile D:\Projects\demo\gulpfile.js
[11:01:13] Starting 'connect'...
[11:01:13] Finished 'connect' after 4.33 ms
[11:01:13] Starting 'html'...
[11:01:13] Finished 'html' after 9.03 ms
[11:01:13] Starting 'open'...
[11:01:13] Finished 'open' after 3.14 ms
[11:01:13] Starting 'default'...
[11:01:13] Finished 'default' after 9.82 μs
Your tasks depends on each other. You should make 'open' depends on 'html' so ot will wait for it to finish:
gulp.task('html', function() {
gulp.src(config.paths.html)
.pipe(gulp.dest(config.paths.dist))
.pipe(connect.reload());
});
gulp.task('connect', function() {
server.listen(config.port);
lrserver.listen(config.livereloadport);
});
gulp.task('open', ['connect', 'html'], function() {
gulp.src('dist/index.html')
.pipe(open({ uri: config.devBaseUrl + ':' + config.port + '/'}));
});
gulp.task('default', ['open']);
So, I found the solution. By default all tasks in gulp are running in parallel. So, you need the task dependency if you want to run them in series, as answered eburger before:
gulp.task('open', ['connect', 'html'], function() {
gulp.src('dist/index.html')
.pipe(open({ uri: config.devBaseUrl + ':' + config.port + '/'}));
});
But beside this you need also get gulp to know when the previous task will has been finished (added return):
gulp.task('html', function() {
return gulp.src(config.paths.html)
.pipe(gulp.dest(config.paths.dist))
.pipe(connect.reload());
});
This solved my issue.

Gulp keeps throwing errors and missing modules

Hi I am working with the web starter kit angular version and am having real issues compiling the code without errors. The main problematic task is the scripts one which keeps giving me random missing modules and uglify/parse problem.
events.js:85
throw er; // Unhandled 'error' event
^
Error
at new JS_Parse_Error (C:\Users\Jensten\webkit\node_modules\gulp
-uglify\node_modules\uglify-js\lib\parse.js:196:18)
at js_error (C:\Users\Jensten\webkit\node_modules\gulp-uglify\no
de_modules\uglify-js\lib\parse.js:204:11)
at croak (C:\Users\Jensten\webkit\node_modules\gulp-uglify\node_
modules\uglify-js\lib\parse.js:679:41)
at token_error (C:\Users\Jensten\webkit\node_modules\gulp-uglify
\node_modules\uglify-js\lib\parse.js:683:9)
at expect_token (C:\Users\Jensten\webkit\node_modules\gulp-uglif
y\node_modules\uglify-js\lib\parse.js:696:9)
at expect (C:\Users\Jensten\webkit\node_modules\gulp-uglify\node
_modules\uglify-js\lib\parse.js:699:36)
at expr_list (C:\Users\Jensten\webkit\node_modules\gulp-uglify\n
ode_modules\uglify-js\lib\parse.js:1202:44)
at C:\Users\Jensten\webkit\node_modules\gulp-uglify\node_modules
\uglify-js\lib\parse.js:1217:23
at C:\Users\Jensten\webkit\node_modules\gulp-uglify\node_modules
\uglify-js\lib\parse.js:722:24
at expr_atom (C:\Users\Jensten\webkit\node_modules\gulp-uglify\n
ode_modules\uglify-js\lib\parse.js:1180:35)
C:\Users\Jensten\webkit\>gulp html
[16:47:01] Using gulpfile ~\pokerstars-webkit\gulpfile.js
[16:47:01] Starting 'html'...
[16:47:02] 'html' errored after 1.54 s
[16:47:02] TypeError: undefined is not a function
at Gulp.<anonymous> (C:\Users\Jensten\webkit\gulpfile.js:130:18)
at module.exports (C:\Users\Jensten\webkit\node_modules\gulp\nod
e_modules\orchestrator\lib\runTask.js:34:7)
at Gulp.Orchestrator._runTask (C:\Users\Jensten\webkit\node_modu
les\gulp\node_modules\orchestrator\index.js:273:3)
at Gulp.Orchestrator._runStep (C:\Users\Jensten\webkit\node_modu
les\gulp\node_modules\orchestrator\index.js:214:10)
at Gulp.Orchestrator.start (C:\Users\Jensten\webkit\node_modules
\gulp\node_modules\orchestrator\index.js:134:8)
at c:\Users\Coutolil\AppData\Roaming\npm\node_modules\gulp\bin\gulp.js:129:2
0
at process._tickCallback (node.js:355:11)
at Function.Module.runMain (module.js:503:11)
at startup (node.js:129:16)
at node.js:814:3
My gulp.js file contains the following:
/**
*
* Web Starter Kit
* Copyright 2014 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*
*/
'use strict';
// Include Gulp & Tools We'll Use
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var del = require('del');
var runSequence = require('run-sequence');
var browserSync = require('browser-sync');
var pagespeed = require('psi');
var reload = browserSync.reload;
var AUTOPREFIXER_BROWSERS = [
'ie >= 10',
'ie_mob >= 10',
'ff >= 30',
'chrome >= 34',
'safari >= 7',
'opera >= 23',
'ios >= 7',
'android >= 4.0',
'bb >= 10'
];
// Lint JavaScript
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')));
});
// Optimize Images
gulp.task('images', function() {
return gulp.src('app/assets/images/**/*')
.pipe($.cache($.imagemin({
progressive: true,
interlaced: true
})))
.pipe(gulp.dest('dist/assets/images'))
.pipe($.size({title: 'images'}));
});
// Copy All Files At The Root Level (app)
gulp.task('copy', function() {
return gulp.src(['app/*', '!app/*.html', '!app/scss', '!app/scripts'], {dot: true})
.pipe(gulp.dest('dist'))
.pipe($.size({title: 'copy'}));
});
// Copy Web Fonts To Dist
gulp.task('fonts', function() {
return gulp.src(['app/assets/fonts/**'])
.pipe(gulp.dest('dist/assets/fonts'))
.pipe($.size({title: 'fonts'}));
});
// Automatically Prefix CSS
gulp.task('styles:css', function() {
return gulp.src('app/styles/css/**/*.css')
.pipe($.changed('app/styles'))
.pipe($.autoprefixer(AUTOPREFIXER_BROWSERS))
.pipe(gulp.dest('app/styles'))
.pipe($.size({title: 'styles:css'}));
});
// Compile Sass For Style Guide Components (app/styles/components)
gulp.task('styles:scss', function() {
var path = require('path');
return gulp.src('app/scss/app.scss')
.pipe($.sass({
style: 'expanded',
precision: 10,
loadPath: ['app/scss']
}))
.on('error', console.error.bind(console))
.pipe($.autoprefixer(AUTOPREFIXER_BROWSERS))
.pipe(gulp.dest('app/assets/styles'))
.pipe(reload({stream:true}))
.pipe($.size({title: 'styles:scss'}));
});
//Watch sass
//---end Watch sass
// Output Final CSS Styles
gulp.task('styles', ['styles:scss', 'styles:css']);
// Scan Your HTML For Assets & Optimize Them
gulp.task('html', function() {
return gulp.src('app/**/*.html')
.pipe($.useref.assets({searchPath: '{.tmp,app}'}))
// Concatenate And Minify JavaScript
.pipe($.if('*.js', $.uglify({preserveComments: 'some'})))
// Remove Any Unused CSS
// commented for now as it doesn't work well with angular (ng-class for example)
/*.pipe($.if('*.css', $.uncss({
html: [
'app/index.html'
],
// CSS Selectors for UnCSS to ignore
ignore: [
'.navdrawer-container.open',
/.app-bar.open/
]
})))*/
// Concatenate And Minify Styles
.pipe($.if('*.css', $.csso()))
.pipe($.useref.restore())
.pipe($.useref())
// Update Production Style Guide Paths
.pipe($.replace('components/components.css', 'components/main.min.css'))
// Minify Any HTML
.pipe($.if('*.html', $.minifyHtml({empty: true})))
// Output Files
.pipe(gulp.dest('dist'))
.pipe($.size({title: 'html'}));
});
gulp.task('scripts', function() {
return gulp.src('app/scripts/**/*.js')
.pipe($.if('*.js', $.uglify({preserveComments: 'some'})))
.pipe($.sourcemaps.init())
.pipe($.concat('app.js'))
.pipe($.sourcemaps.write('./'))
.pipe(gulp.dest('app/assets/scripts'));
});
gulp.task('vendor', function() {
var mainBowerFiles = require('main-bower-files');
return gulp.src(mainBowerFiles(/* options */))
.pipe($.if('*.js', $.uglify({preserveComments: 'some'})))
.pipe($.sourcemaps.init())
.pipe($.concat('vendor.js'))
.pipe($.sourcemaps.write('./'))
.pipe(gulp.dest('app/assets/scripts'));
})
// Clean Output Directory
gulp.task('clean', del.bind(null, ['.tmp', 'dist']));
// Watch Files For Changes & Reload
gulp.task('serve', function() {
browserSync({
open: false,
notify: true,
server: {
baseDir: ['.tmp', 'app']
}
});
gulp.watch(['app/**/*.html'], reload);
gulp.watch(['app/scss/**/*.scss'], ['styles:scss']);
// gulp.watch(['{.tmp,app}/assets/styles/**/*.css'], ['styles:css']);
gulp.watch(['app/scripts/**/*.js'], [/*'jshint',*/ 'scripts', reload]);
gulp.watch(['app/assets/images/**/*'], reload);
});
// Build and serve the output from the dist build
gulp.task('serve:dist', ['default'], function() {
browserSync({
open: false,
notify: true,
server: {
baseDir: 'dist'
}
});
});
// Build Production Files, the Default Task
gulp.task('default', ['clean'], function(cb) {
runSequence('styles', 'vendor', 'scripts', ['jshint', 'html', 'images', 'fonts', 'copy'], cb);
});
// Run PageSpeed Insights
// Update `url` below to the public URL for your site
gulp.task('pagespeed', pagespeed.bind(null, {
// By default, we use the PageSpeed Insights
// free (no API key) tier. You can use a Google
// Developer API key if you have one. See
// http://goo.gl/RkN0vE for info key: 'YOUR_API_KEY'
url: 'https://example.com',
strategy: 'mobile'
}));
// Load custom tasks from the `tasks` directory
try {
require('require-dir')('tasks');
} catch(err) {
}
I am happy to use a different file, all I want is to make sure that: Angular, SASS, compression, and file output to the assets directory are working. I am currently able to run the project but the default task obviously does not run on gulp serve, hence why I was unable to see any errors before.
Could anyone point me in the right direction?
I had the same problem just now,then i realized that I haven't added the relative Plug-in to gulp. After I add it,then it's solved!
maybe this is the solution.
Place your devDependencies at correct place in package.json file as shown below
{
"name": "my-project",
"private": true,
"devDependencies": {
//dependencies are place here
},
"engines": {
"node": ">=0.10.0"
}
}