Deploying Angular2 Application - Folder Structure Changes - html

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']);

Related

Gulp change paths/links in html files after copying to dist directory

I created a static website and I use gulp for automation. Now, I copy also my html files to dist directory using gulp pages but when I checked that directory and open any html files, stylesheets and all other links are broken due to relative paths. Is there a way to change the paths for the stylesheets and images while copying html to dist directory?
gulpfile.js
"use strict";
const gulp = require("gulp");
const sass = require("gulp-sass");
const imagemin = require("gulp-imagemin");
const htmlmin = require("gulp-htmlmin");
const browserSync = require("browser-sync").create();
const sassPaths = ["./node_modules"];
function style() {
return gulp
.src("./app/scss/**/*.scss")
.pipe(sass({ includePaths: sassPaths, outputStyle: "compressed" }))
.pipe(gulp.dest("./app/dist/css"))
.pipe(browserSync.stream());
}
function images() {
return gulp
.src("./app/images/**/*")
.pipe(imagemin())
.pipe(gulp.dest("/app/dist/images"));
}
function pages() {
return gulp
.src(["./app/**/*html"])
.pipe(
htmlmin({
collapseWhitespace: true,
removeComments: true
})
)
.pipe(gulp.dest("./app/dist"));
}
function watch() {
browserSync.init({
server: {
baseDir: "./app"
}
});
gulp.watch("./app/scss/**/*.scss", style, images);
gulp.watch("./app/**/*.html").on("change", browserSync.reload);
}
exports.style = style;
exports.images = images;
exports.pages = pages;
exports.watch = watch;
I want to change the generated files inside dist directory from
<link rel="stylesheet" href="./dist/css/app.css">
to
<link rel="stylesheet" href="./css/app.css" />
Have a look at gulp-processhtml or a similar package like gulp-useref.
And then in your html file you would have something like:
<!-- build:css ./css/app.css -->
<link rel="stylesheet" href="./dist/css/app.css">
<!-- /build -->
that would change your link to <link rel="stylesheet" href="./css/app.css" />
const modifyHTMLlinks = require("gulp-processhtml"); // or try gulp-useref
function pages() {
return gulp
.src(["./app/**/*html"])
.pipe(modifyHTMLlinks())
.pipe(
htmlmin({
collapseWhitespace: true,
removeComments: true
})
)
.pipe(gulp.dest("./app/dist"));
}

How to append the main.css file through Roots's Sage gulpfile?

I'm very new to gulp and seeing as how complex the Roots's Sage gulpfile is, I'm so lost as to which block of code I should put in my code in.
The usage examples for both packages is as follows:
CSS Shrink
var gulp = require('gulp');
var cssshrink = require('gulp-cssshrink');
gulp.task('default', function() {
gulp.src('css/**/*.css')
.pipe(cssshrink())
.pipe(gulp.dest('dist/css/'));
});
Combine Media Queries
var cmq = require('gulp-combine-media-queries');
gulp.task('cmq', function () {
gulp.src('src/**/*.css')
.pipe(cmq({
log: true
}))
.pipe(gulp.dest('dist'));
});
Manifest.json file:
{
"dependencies": {
"main.js": {
"files": [
"scripts/main.js"
],
"main": true
},
"main.css": {
"files": [
"styles/main.scss"
],
"main": true
},
"customizer.js": {
"files": [
"scripts/customizer.js"
]
},
"jquery.js": {
"bower": [
"jquery"
]
}
},
"config": {
"devUrl": "http://yaharga/"
}
}
I tried to put it in the Styles task at the gulpfile.js, but nothing happened:
// ## Globals
var argv = require('minimist')(process.argv.slice(2));
var autoprefixer = require('gulp-autoprefixer');
var browserSync = require('browser-sync').create();
var changed = require('gulp-changed');
var concat = require('gulp-concat');
var flatten = require('gulp-flatten');
var gulp = require('gulp');
var gulpif = require('gulp-if');
var imagemin = require('gulp-imagemin');
var jshint = require('gulp-jshint');
var lazypipe = require('lazypipe');
var less = require('gulp-less');
var merge = require('merge-stream');
var cssNano = require('gulp-cssnano');
var plumber = require('gulp-plumber');
var rev = require('gulp-rev');
var runSequence = require('run-sequence');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var uglify = require('gulp-uglify');
var cmq = require('gulp-combine-media-queries');
var cssshrink = require('gulp-cssshrink');
// See https://github.com/austinpray/asset-builder
var manifest = require('asset-builder')('./assets/manifest.json');
// `path` - Paths to base asset directories. With trailing slashes.
// - `path.source` - Path to the source files. Default: `assets/`
// - `path.dist` - Path to the build directory. Default: `dist/`
var path = manifest.paths;
// `config` - Store arbitrary configuration values here.
var config = manifest.config || {};
// `globs` - These ultimately end up in their respective `gulp.src`.
// - `globs.js` - Array of asset-builder JS dependency objects. Example:
// ```
// {type: 'js', name: 'main.js', globs: []}
// ```
// - `globs.css` - Array of asset-builder CSS dependency objects. Example:
// ```
// {type: 'css', name: 'main.css', globs: []}
// ```
// - `globs.fonts` - Array of font path globs.
// - `globs.images` - Array of image path globs.
// - `globs.bower` - Array of all the main Bower files.
var globs = manifest.globs;
// `project` - paths to first-party assets.
// - `project.js` - Array of first-party JS assets.
// - `project.css` - Array of first-party CSS assets.
var project = manifest.getProjectGlobs();
// CLI options
var enabled = {
// Enable static asset revisioning when `--production`
rev: argv.production,
// Disable source maps when `--production`
maps: !argv.production,
// Fail styles task on error when `--production`
failStyleTask: argv.production,
// Fail due to JSHint warnings only when `--production`
failJSHint: argv.production,
// Strip debug statments from javascript when `--production`
stripJSDebug: argv.production
};
// Path to the compiled assets manifest in the dist directory
var revManifest = path.dist + 'assets.json';
// ## Reusable Pipelines
// See https://github.com/OverZealous/lazypipe
// ### CSS processing pipeline
// Example
// ```
// gulp.src(cssFiles)
// .pipe(cssTasks('main.css')
// .pipe(gulp.dest(path.dist + 'styles'))
// ```
var cssTasks = function(filename) {
return lazypipe()
.pipe(function() {
return gulpif(!enabled.failStyleTask, plumber());
})
.pipe(function() {
return gulpif(enabled.maps, sourcemaps.init());
})
.pipe(function() {
return gulpif('*.less', less());
})
.pipe(function() {
return gulpif('*.scss', sass({
outputStyle: 'nested', // libsass doesn't support expanded yet
precision: 10,
includePaths: ['.'],
errLogToConsole: !enabled.failStyleTask
}));
})
.pipe(concat, filename)
.pipe(autoprefixer, {
browsers: [
'last 2 versions',
'android 4',
'opera 12'
]
})
.pipe(cssNano, {
safe: true
})
.pipe(function() {
return gulpif(enabled.rev, rev());
})
.pipe(function() {
return gulpif(enabled.maps, sourcemaps.write('.', {
sourceRoot: 'assets/styles/'
}));
})();
};
// ### JS processing pipeline
// Example
// ```
// gulp.src(jsFiles)
// .pipe(jsTasks('main.js')
// .pipe(gulp.dest(path.dist + 'scripts'))
// ```
var jsTasks = function(filename) {
return lazypipe()
.pipe(function() {
return gulpif(enabled.maps, sourcemaps.init());
})
.pipe(concat, filename)
.pipe(uglify, {
compress: {
'drop_debugger': enabled.stripJSDebug
}
})
.pipe(function() {
return gulpif(enabled.rev, rev());
})
.pipe(function() {
return gulpif(enabled.maps, sourcemaps.write('.', {
sourceRoot: 'assets/scripts/'
}));
})();
};
// ### Write to rev manifest
// If there are any revved files then write them to the rev manifest.
// See https://github.com/sindresorhus/gulp-rev
var writeToManifest = function(directory) {
return lazypipe()
.pipe(gulp.dest, path.dist + directory)
.pipe(browserSync.stream, {match: '**/*.{js,css}'})
.pipe(rev.manifest, revManifest, {
base: path.dist,
merge: true
})
.pipe(gulp.dest, path.dist)();
};
// ## Gulp tasks
// Run `gulp -T` for a task summary
// ### Styles
// `gulp styles` - Compiles, combines, and optimizes Bower CSS and project CSS.
// By default this task will only log a warning if a precompiler error is
// raised. If the `--production` flag is set: this task will fail outright.
gulp.task('styles', ['wiredep'], function() {
var merged = merge();
manifest.forEachDependency('css', function(dep) {
var cssTasksInstance = cssTasks(dep.name);
if (!enabled.failStyleTask) {
cssTasksInstance.on('error', function(err) {
console.error(err.message);
this.emit('end');
});
}
merged.add(gulp.src(dep.globs, {base: 'styles'})
.pipe(cssTasksInstance));
});
/************************* This is where I added it! *************************/
gulp.src(path.dist + 'styles/main.css')
.pipe(cssshrink())
.pipe(cmq())
.pipe(gulp.dest(path.dist + 'styles/main.css'));
return merged
.pipe(writeToManifest('styles'));
});
// ### Scripts
// `gulp scripts` - Runs JSHint then compiles, combines, and optimizes Bower JS
// and project JS.
gulp.task('scripts', ['jshint'], function() {
var merged = merge();
manifest.forEachDependency('js', function(dep) {
merged.add(
gulp.src(dep.globs, {base: 'scripts'})
.pipe(jsTasks(dep.name))
);
});
return merged
.pipe(writeToManifest('scripts'));
});
// ### Fonts
// `gulp fonts` - Grabs all the fonts and outputs them in a flattened directory
// structure. See: https://github.com/armed/gulp-flatten
gulp.task('fonts', function() {
return gulp.src(globs.fonts)
.pipe(flatten())
.pipe(gulp.dest(path.dist + 'fonts'))
.pipe(browserSync.stream());
});
// ### Images
// `gulp images` - Run lossless compression on all the images.
gulp.task('images', function() {
return gulp.src(globs.images)
.pipe(imagemin({
progressive: true,
interlaced: true,
svgoPlugins: [{removeUnknownsAndDefaults: false}, {cleanupIDs: false}]
}))
.pipe(gulp.dest(path.dist + 'images'))
.pipe(browserSync.stream());
});
// ### JSHint
// `gulp jshint` - Lints configuration JSON and project JS.
gulp.task('jshint', function() {
return gulp.src([
'bower.json', 'gulpfile.js'
].concat(project.js))
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish'))
.pipe(gulpif(enabled.failJSHint, jshint.reporter('fail')));
});
// ### Clean
// `gulp clean` - Deletes the build folder entirely.
gulp.task('clean', require('del').bind(null, [path.dist]));
// ### Watch
// `gulp watch` - Use BrowserSync to proxy your dev server and synchronize code
// changes across devices. Specify the hostname of your dev server at
// `manifest.config.devUrl`. When a modification is made to an asset, run the
// build step for that asset and inject the changes into the page.
// See: http://www.browsersync.io
gulp.task('watch', function() {
browserSync.init({
files: ['{lib,templates}/**/*.php', '*.php'],
proxy: config.devUrl,
snippetOptions: {
whitelist: ['/wp-admin/admin-ajax.php'],
blacklist: ['/wp-admin/**']
}
});
gulp.watch([path.source + 'styles/**/*'], ['styles']);
gulp.watch([path.source + 'scripts/**/*'], ['jshint', 'scripts']);
gulp.watch([path.source + 'fonts/**/*'], ['fonts']);
gulp.watch([path.source + 'images/**/*'], ['images']);
gulp.watch(['bower.json', 'assets/manifest.json'], ['build']);
});
// ### Build
// `gulp build` - Run all the build tasks but don't clean up beforehand.
// Generally you should be running `gulp` instead of `gulp build`.
gulp.task('build', function(callback) {
runSequence('styles',
'scripts',
['fonts', 'images'],
callback);
});
// ### Wiredep
// `gulp wiredep` - Automatically inject Less and Sass Bower dependencies. See
// https://github.com/taptapship/wiredep
gulp.task('wiredep', function() {
var wiredep = require('wiredep').stream;
return gulp.src(project.css)
.pipe(wiredep())
.pipe(changed(path.source + 'styles', {
hasChanged: changed.compareSha1Digest
}))
.pipe(gulp.dest(path.source + 'styles'));
});
// ### Gulp
// `gulp` - Run a complete build. To compile for production run `gulp --production`.
gulp.task('default', ['clean'], function() {
gulp.start('build');
});
Ideally, I would need to capture the main.css code and implement the cmq and cssshrink to it just before it is finally exported into the distribution folder.
I followed the post on Roots Discourse to help me do it; will update with full answer once done.

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.

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"
}
}

How to detect css theme and work only with this theme?

I have a project in which there are about 30 css themes. It means I have the next css files structure:
src/
themes/
default/
a.scss
b.scss
rockStar/
a.scss
b.scss
oneMoreTheme/
a.scss
b.scss
dist/
themes/
default/
styles.css
rockStar/
styles.css
oneMoreTheme/
styles.css
Here is just example of gulpfile:
var gulp = require('gulp'),
glob = require('glob'),
path = require('path'),
_ = require('underscore'),
$ = require('gulp-load-plugins')(),
options = {};
options.themes = [
'default',
'rockStar',
'oneMoreTheme'
];
gulp.task('styles', function () {
_.each(options.themes, function(themeName, themeKey) {
gulp.src('src/themes/' + themeName + '/**/*.scss')
.pipe($.concat('styles.scss'))
.pipe($.sass())
.pipe(gulp.dest('dist/themes/' + themeName + '/'));
});
});
gulp.task('watch', function () {
gulp.watch('src/**/*.*', ['styles']);
});
In my gulp file I have a task "styles", which compiles scss files from each theme and puts compiled files to dist folder.
And I have task "watch" which run "styles" task when any scss file form any source theme changes. It works, but it takes much time because of lots of themes!
How can my task "watch" detect from which theme files changes and run task "styles" only for this changed theme?
That is indeed a tough one, but here is a solution. Please refer to the comments in the code for an explanation.
version 1
var gulp = require('gulp');
var merge = require('merge2');
var $ = require('gulp-load-plugins')();
var path = require('path');
var options = {};
options.themes = [
'default',
'rockStar',
'oneMoreTheme'
];
// we extract the task itself to a new function
// this allows us to reuse it
var styleTask = function(themeName) {
return gulp.src('src/themes/' + themeName + '/**/*.scss')
.pipe($.concat('styles.scss'))
.pipe($.sass())
.pipe(gulp.dest('dist/themes/' + themeName + '/'));
}
// we adapt the style task to use that function
// please note that I switched _.each for merge
// this allows you to work with streams!
gulp.task('styles', function() {
var tasks = themes.map(styleTask);
return merge(tasks);
});
// here we set up a new watcher. Instead of running 'styles'
// we filter the theme directory from the file that has changed
// and run the styleTask function
gulp.task('default', function() {
var watcher = gulp.watch('src/themes/**/*.scss', function(e) {
var theme = path
.relative(__dirname, e.path)
.substr('src/themes/'.length)
.split('/')[0];
console.log('rebuilding ' + theme);
return styleTask('theme');
});
});
version 2
// same as above except the default task. we save the theme
// we want to build in a file
var singleTheme;
// and call the styleTask function should it be set
gulp.task('single-style', function(done) {
if(singleTheme) {
return styleTask(singleTheme);
} else {
done();
}
});
// here we have a watcher that calls single-style, but before calling
// it gets the right themename.
gulp.task('default', function() {
var watcher = gulp.watch('src/themes/**/*.scss', 'single-style');
watcher.on('change', function(e) {
singleTheme = path
.relative(__dirname, e.path)
.substr('src/themes/'.length)
.split('/')[0];
console.log('rebuilding ' + theme);
})
})
I hope this helped.
Update If you want to run more tasks and have a status call on if they ended, please go for version 2. Than you can add all the tasks you want to run in
gulp.task('default', function() {
var watcher = gulp.watch('src/themes/**/*.scss', ['single-style', 'another-task']);
watcher.on('change', function(e) {
singleTheme = path
.relative(__dirname, e.path)
.substr('src/themes/'.length)
.split('/')[0];
console.log('rebuilding ' + theme);
})
})
Instead of gulp.run you can use gulp.start.