I was experiencing a known issue with Angular UI Grid where some of my fonts would look Korean in production.
I applied a certain fix by adding the following CSS:
#font-face {
font-family: 'ui-grid';
src: url('../fonts/ui-grid.eot');
src: url('../fonts/ui-grid.eot#iefix') format('embedded-opentype'), url('../fonts/ui-grid.woff') format('woff'), url('../fonts/ui-grid.ttf?') format('truetype'), url('../fonts/ui-grid.svg?#ui-grid') format('svg');
font-weight: normal;
font-style: normal;
}
This fixed the problem in production, but now in development I get these errors in the browser console:
GET http://localhost:9000/fonts/ui-grid.woff
GET http://localhost:9000/fonts/ui-grid.ttf? 404 (Not Found)
I'm using Gulp as my build tool. I can get the errors to go away by adding a fonts directory to .tmp/serve and manually copying bower_components/angular-ui-grid/ui-grid.* there, but this of course isn't an acceptable permanent solution.
My Gulp configuration already copies my font files to public/fonts in production. How can I achieve something similar in development?
Here's my gulp/build.js. I'm a Gulp novice.
'use strict';
var gulp = require('gulp');
var $ = require('gulp-load-plugins')({
pattern: ['gulp-*', 'main-bower-files', 'uglify-save-license', 'del']
});
module.exports = function(options) {
gulp.task('partials', ['markups'], function () {
return gulp.src([
options.src + '/{app,components}/**/*.html',
options.tmp + '/serve/{app,components}/**/*.html'
])
.pipe($.minifyHtml({
empty: true,
spare: true,
quotes: true
}))
.pipe($.angularTemplatecache('templateCacheHtml.js', {
module: 'freightVerify'
}))
.pipe(gulp.dest(options.tmp + '/partials/'));
});
gulp.task('html', ['inject', 'partials'], function () {
var partialsInjectFile = gulp.src(options.tmp + '/partials/templateCacheHtml.js', { read: false });
var partialsInjectOptions = {
starttag: '<!-- inject:partials -->',
ignorePath: options.tmp + '/partials',
addRootSlash: false
};
var htmlFilter = $.filter('*.html');
var jsFilter = $.filter('**/*.js');
var cssFilter = $.filter('**/*.css');
var assets;
return gulp.src(options.tmp + '/serve/*.html')
.pipe($.inject(partialsInjectFile, partialsInjectOptions))
.pipe(assets = $.useref.assets())
.pipe($.rev())
.pipe(jsFilter)
.pipe($.ngAnnotate())
.pipe($.uglify({ preserveComments: $.uglifySaveLicense })).on('error', options.errorHandler('Uglify'))
.pipe(jsFilter.restore())
.pipe(cssFilter)
.pipe($.replace('../../bower_components/bootstrap-sass-official/assets/fonts/bootstrap/', '../fonts/'))
.pipe($.csso())
.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(options.dist + '/'))
.pipe($.size({ title: options.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(options.dist + '/fonts/'));
});
gulp.task('other', function () {
return gulp.src([
options.src + '/**/*',
'!' + options.src + '/**/*.{html,css,js,scss,jade}'
])
.pipe(gulp.dest(options.dist + '/'));
});
gulp.task('clean', function (done) {
$.del([options.dist + '/', options.tmp + '/'], done);
});
gulp.task('config', function() {
gulp.src(options.src + '/app/config/config.json')
.pipe($.ngConfig('freightVerify', {
wrap: '(function () {\n\'use strict\';\n/*jshint ignore:start*/\n return <%= module %> /*jshint ignore:end*/\n})();',
createModule: false,
environment: process.env.NODE_ENV || 'development'
}))
.pipe(gulp.dest(options.src + '/app/config'));
});
gulp.task('build', ['config', 'html', 'fonts', 'other']);
};
And here's the gulpfile itself, if it helps:
'use strict';
var gulp = require('gulp');
var gutil = require('gulp-util');
var _ = require('lodash');
var wrench = require('wrench');
var options = {
src: 'src',
dist: '../public',
tmp: '.tmp',
e2e: 'e2e',
errorHandler: function(title) {
return function(err) {
gutil.log(gutil.colors.red('[' + title + ']'), err.toString());
this.emit('end');
};
}
};
wrench.readdirSyncRecursive('./gulp').filter(function(file) {
return (/\.(js|coffee)$/i).test(file);
}).map(function(file) {
require('./gulp/' + file)(options);
});
gulp.task('default', ['clean'], function() {
gulp.start('build');
});
gulp.task('heroku:production', function() {
gulp.start('build');
})
I came up while a solution that works, although it's not very DRY. I hope someone else suggests a better solution.
// This is the original fonts task
gulp.task('fonts', function () {
return gulp.src($.mainBowerFiles())
.pipe($.filter('**/*.{eot,svg,ttf,woff,woff2}'))
.pipe($.flatten())
.pipe(gulp.dest(options.dist + '/fonts/'));
});
// This is my new task, only slightly different
gulp.task('fonts:dev', function () {
return gulp.src($.mainBowerFiles())
.pipe($.filter('**/*.{eot,svg,ttf,woff,woff2}'))
.pipe($.flatten())
.pipe(gulp.dest(options.tmp + '/serve/fonts/'));
});
I added the fonts:dev task as shown above, and I added it as a dep to my serve task.
Related
I try to build my React project with gulpfile.js in production mode so the query developer tools show green color in browser tab. However, it still failed with dead code elimination error, which means development version is still detected in react developer tools.
I have already tried many ways to eliminate this error. One of the closest solution is to add 'unreachable-branch-transform' and gulpif argv in browserify part in gulpfile.js. Please check gulpfile.js content below.
var gulp = require('gulp');
var imagemin = require('gulp-imagemin');
var clean = require('gulp-clean');
var argv = require('yargs').argv;
var gulpif = require('gulp-if');
var browserify = require('browserify');
var watchify = require('watchify');
var babelify = require('babelify');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var envify = require('envify/custom');
var replace = require('gulp-replace');
var gutil = require('gulp-util');
var uglifyCSS = require('gulp-uglifycss');
var uglifyJS = require('gulp-uglify');
var version_append = require('gulp-version-append');
var connect = require('gulp-connect');
var historyApiFallback = require('connect-history-api-fallback');
var workboxBuild = require('workbox-build');
var prefixer = require('autoprefixer');
var postcss = require('gulp-postcss');
var concat = require('gulp-concat');
var less = require('gulp-less');
var chalk = require("chalk");
var path = require('path');
var exec = require('child_process').exec;
var paths = {
public_view_src : "view/",
public_view_dest : "public/",
images: 'img/**/*',
css :
[
"node_modules/bootstrap/dist/css/bootstrap.min.css",
"node_modules/font-awesome/css/font-awesome.min.css",
"node_modules/animate.css/animate.min.css",
"node_modules/lato-font/css/lato-font.min.css"
],
js :
{
plugins: [
"node_modules/clientjs/dist/client.min.js",
"node_modules/jquery.payment/lib/jquery.payment.min.js"
],
vendor: [
"node_modules/jquery/dist/jquery.min.js",
"node_modules/bootstrap/dist/js/bootstrap.min.js"
],
react : ["./src/app.js", "./src/**/*.js"],
app: "./script/*.js",
register_service_worker: 'service_worker/register_service_worker.js'
},
fonts : [
"node_modules/font-awesome/fonts/**/*",
"node_modules/bootstrap/dist/fonts/**/*"
],
less : ["less/style.less", "less/**/*.less", "node_modules/roboto-fontface-pre-css/css/roboto-fontface.less"],
service_worker: 'service_worker/service-worker.js'
};
function build_service_worker() {
console.info('Workbox libraries copying started.');
return workboxBuild.copyWorkboxLibraries(paths.public_view_dest).then((workboxDirectoryName) => {
console.info('Workbox libraries copied to: ' + workboxDirectoryName);
return workboxBuild.injectManifest({
swSrc: `${paths.service_worker}`,
swDest: `${paths.public_view_dest}/service-worker.js`,
maximumFileSizeToCacheInBytes: 50000000,
globDirectory: paths.public_view_dest,
globPatterns: ['**\/*.{html,js,css,png,svg,otf,ttf,eot,woff,woff2}'],
globIgnores: ['service-worker.js', 'manifest.json'].concat([`**/workbox*/*.js*`])
}).then((result) => {
result.warnings.forEach(console.warn);
console.info(`${result.count} files will be precached, totaling ${result.size} bytes.`);
console.info(`import ${paths.public_view_dest}${workboxDirectoryName}/workbox-sw.js to service-worker-script`);
gulp.src(`${paths.public_view_dest}/service-worker.js`)
.pipe(replace('#workbox-sw', `${workboxDirectoryName}/workbox-sw.js`))
.pipe(gulp.dest(paths.public_view_dest));
console.info('Service worker generation completed.');
});
}).catch((error) => {
console.warn('Workbox lbraries copying failed: ' + error);
});
}
// map error
function map_error(err) {
if (err.fileName) {
gutil.log(chalk.red(err.name)
+ ': '
+ chalk.yellow(err.fileName.replace(__dirname, ''))
+ ': '
+ 'Line '
+ chalk.magenta(err.lineNumber)
+ ' & '
+ 'Column '
+ chalk.magenta(err.columnNumber || err.column)
+ ': '
+ chalk.blue(err.description));
} else {
var message = err.message.replace(__dirname + "/", "");
gutil.log(chalk.red(err.name)
+ ': '
+ chalk.yellow(message));
}
this.emit('end');
}
function prevent_cache_assets(){
return function(){
return gulp.src(path.join(__dirname, paths.public_view_src + '*.html'))
.pipe(version_append(['html', 'js', 'css'],
{
appendType: 'timestamp',
versionFile: 'version.json'
}))
.pipe(gulp.dest(paths.public_view_dest));
};
}
function reactScript(watch) {
var bundler, rebundle;
bundler = browserify(paths.js.react[0], {
basedir: __dirname,
// debug: watch,
cache: {}, // required for watchify
packageCache: {}, // required for watchify
fullPaths: watch, // required to be true only for watchify
debug: argv.production ? false : true
});
if(watch) {
bundler = watchify(bundler);
}
bundler.transform('unreachable-branch-transform', {
global: true
});
bundler.transform(envify({
_: 'purge',
MODE: process.env.MODE
}));
bundler.transform(babelify.configure({
"plugins": ["object-assign"]
}));
rebundle = function() {
console.log("packing react");
var stream = bundler.bundle();
stream.on('error', map_error);
stream = stream.pipe(source('app.min.js'));
if(!watch) {
stream = stream.pipe(gulpif(argv.production, buffer()));
//stream = stream.pipe(uglifyJS());
}
return stream.pipe(gulp.dest('public/assets/dist'));
};
bundler.on('update', rebundle);
bundler.on('log', gutil.log);
return rebundle();
}
function es(){
return gulp.src('public/assets/dist/app.min.js')
.pipe(uglifyJS())
.pipe(gulp.dest('public/assets/dist'));
}
gulp.task('mini', es);
// task for stage or production
gulp.task('min', ['js', 'vendor', 'less', 'copyfonts', 'prevent_cache_assets']);
// init task
gulp.task('init', ['js', 'vendor', 'less', 'copyfonts', 'watch', 'prevent_cache_assets'], function () {
gulp.watch([paths.public_view_src + '**\/*', paths.service_worker, paths.public_view_dest + 'assets/**\/*.{html,js,css,png,svg,otf,ttf,eot,woff,woff2}'], ['build-service-worker']);
return build_service_worker();
});
// imagemin
gulp.task('clean-images-dest', function(){
return gulp.src('public/assets/img', {read: false})
.pipe(clean());
});
gulp.task('images', ['clean-images-dest'], function(){
return gulp.src(paths.images)
.pipe(imagemin())
.pipe(gulp.dest('public/assets/img'));
});
// react
gulp.task('react', function () {
return reactScript(false);
});
// copy fontawesome fonts task
gulp.task('copyfonts', function() {
return gulp.src(paths.fonts)
.on('error', map_error)
.pipe(gulp.dest('public/assets/css/fonts'));
});
// less task
gulp.task('less', ['images'], function(){
var l = less();
l.on('error', map_error);
return gulp.src(paths.less[0])
.pipe(l)
.pipe(postcss([prefixer({ browsers: ["> 0%"] })]))
.pipe(uglifyCSS())
.pipe(gulp.dest('public/assets/css'));
});
// copy lato fonts
gulp.task('cp-myriad-font', function(){
return gulp.src(['./node_modules/myriad-font/fonts/myriad/myriad-set-pro_text.woff', './node_modules/myriad-font/fonts/myriad/myriad-set-pro_bold.woff'])
.pipe(gulp.dest('public/assets/css/fonts'));
});
// vendor task
gulp.task('vendor', ['cp-myriad-font'], function(){
return gulp.src(paths.css)
.on('error', map_error)
.pipe(concat('vendor.css'))
.pipe(uglifyCSS())
.pipe(gulp.dest('public/assets/css/vendor'));
});
// prevent cache task
gulp.task('prevent_cache_assets', prevent_cache_assets());
// javascript task
gulp.task('js', ['js_vendor', 'js_plugins', 'js_register_service_worker'], function(){
return gulp.src(paths.js.app)
.on('error', map_error)
.pipe(concat('app.min.js'))
.pipe(uglifyJS())
.pipe(gulp.dest('public/assets/js'));
});
gulp.task('js_vendor', function(){
return gulp.src(paths.js.vendor)
.on('error', map_error)
.pipe(concat('vendor.min.js'))
.pipe(uglifyJS())
.pipe(gulp.dest('public/assets/js'));
});
gulp.task('js_plugins', function(){
return gulp.src(paths.js.plugins)
.on('error', map_error)
.pipe(concat('plugins.min.js'))
.pipe(uglifyJS())
.pipe(gulp.dest('public/assets/js'));
});
gulp.task('js_register_service_worker', function(){
return gulp.src(paths.js.register_service_worker)
.on('error', map_error)
.pipe(concat('register_service_worker.min.js'))
.pipe(uglifyJS())
.pipe(gulp.dest('public/assets/js'));
});
// task to run api
gulp.task('api', function(cb){
exec('cd ../mp-wallet-api && nodemon', function(err, stdout, stderr){
console.log(stdout);
console.log(stderr);
cb(err);
});
});
// watcher
gulp.task('watch', function(){
gulp.watch(paths.less, ['less']);
gulp.watch(paths.js.app, ['js']);
gulp.watch(paths.js.plugins, ['js']);
gulp.watch(paths.js.vendor, ['js']);
gulp.watch(paths.js.register_service_worker, ['js']);
gulp.watch(paths.css, ['vendor']);
gulp.watch(paths.fonts, ['copyfonts']);
gulp.watch(paths.public_view_src + '*.html', ['prevent_cache_assets']);
return reactScript(true);
});
gulp.task('connect', function() {
connect.server({
port: 3000,
root: [paths.public_view_dest],
middleware: function(connect, opt){
return [historyApiFallback({})];
},
fallback: 'index.html'
});
connect.serverClose();
});
gulp.task('set-production-env', function() {
return process.env.NODE_ENV = 'production';
});
gulp.task('default', ['set-production-env', 'init']);
gulp.task('serve', ['set-production-env', 'init', 'connect']);
gulp.task('with-api', ['set-production-env', 'api', 'init']);
gulp.task('build-service-worker', function () {
return build_service_worker();
});
My React project is only using gulp and browserify inside gulpfile.js, so this project doesn't use any build tools listed in documentation link below (grunt, webpack, browserify (standalone),rollup).
https://reactjs.org/docs/optimizing-performance.html
Do you have any suggestion how to eliminate dead code elimination, but only by using gulp and browserify inside it ? Thanks in advance.
I'm trying to customize a template for a demo of a webapp built on AngularJS using MacOS Sierra 10.13.6. I've installed Gulp but when I launch gulp serve return this error without launching the local server:
assert.js:337 throw err; ^
AssertionError [ERR_ASSERTION]: Task function must be specified at
Gulp.set [as _setTask]
(/Users/barkia/Desktop/Elysium/repos/elysium-webapp/material/node_modules/undertaker/lib/set-task.js:10:3)
at Gulp.task
(/Users/barkia/Desktop/Elysium/repos/elysium-webapp/material/node_modules/undertaker/lib/task.js:13:8)
at Object.
(/Users/barkia/Desktop/Elysium/repos/elysium-webapp/material/gulpfile.js:9:6)
at Module._compile (internal/modules/cjs/loader.js:689:30) at
Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32) at
tryModuleLoad (internal/modules/cjs/loader.js:538:12) at
Function.Module._load (internal/modules/cjs/loader.js:530:3) at
Module.require (internal/modules/cjs/loader.js:637:17) at require
(internal/modules/cjs/helpers.js:20:18)
Here is the gulpfile.js actually in ~/Desktop/Elysium/repos/elysium-webapp/material/gulpfile.js
I've deleted the previous error regarding /usr/local/share/man/man1/gulp.1 by launching npm uninstall -g gulp and after npm install -g gulp but I still have that issues on assert.js:337
var gulp = require('gulp');
var args = require('yargs').argv;
var browserSync = require('browser-sync');
var config = require('./gulp.config')();
var del = require('del');
var $ = require('gulp-load-plugins')({lazy: true});
gulp.task('help', $.taskListing);
gulp.task('default', ['help']);
gulp.task('vet', function() {
log('Analyzing source with JSHint and JSCS');
return gulp
.src(config.alljs)
.pipe($.if(args.verbose, $.print()))
.pipe($.jscs())
.pipe($.jshint())
.pipe($.jshint.reporter('jshint-stylish', {verbose: true}))
.pipe($.jshint.reporter('fail'));
});
gulp.task('clean-tmp', function(done) {
var files = config.tmp;
clean(files, done);
});
gulp.task('clean', function(done) {
var delconfig = [].concat(config.dist, config.tmp);
log('Cleaning ' + $.util.colors.blue(delconfig));
del(delconfig, done);
});
gulp.task('clean-all', function(done) {
var delconfig = config.allToClean;
log('Cleaning ' + $.util.colors.blue(delconfig));
clean(delconfig, done);
});
gulp.task('pug-docs', function() {
log('Compiling docs pug --> html');
var options = {
pretty: false
}
return gulp
.src(config.docsPug)
.pipe($.plumber({errorHandler: swallowError}))
.pipe($.pug(options))
.pipe(gulp.dest(config.docs));
});
gulp.task('less', function() {
log('Compiling Less --> CSS');
return gulp
.src(config.less)
.pipe($.plumber({errorHandler: swallowError}))
.pipe($.less())
.pipe($.autoprefixer())
.pipe(gulp.dest(config.tmp));
});
gulp.task('less-watcher', function() {
gulp.watch([config.less], ['less']);
});
gulp.task('sass', function() {
log('Compiling Sass --> CSS');
var sassOptions = {
outputStyle: 'nested' // nested, expanded, compact, compressed
};
return gulp
.src(config.sass)
.pipe($.plumber({errorHandler: swallowError}))
.pipe($.sourcemaps.init())
.pipe($.sass(sassOptions))
.pipe($.autoprefixer())
.pipe($.sourcemaps.write())
.pipe(gulp.dest(config.tmp + '/styles'));
});
gulp.task('sass-min', function() {
log('Compiling Sass --> minified CSS');
var sassOptions = {
outputStyle: 'compressed' // nested, expanded, compact, compressed
};
return gulp
.src(config.sass)
.pipe($.plumber({errorHandler: swallowError}))
.pipe($.sass(sassOptions))
.pipe($.autoprefixer())
.pipe(gulp.dest(config.tmp + '/styles'));
})
gulp.task('sass-watcher', function() {
gulp.watch([config.sass], ['sass']);
});
gulp.task('inject', function() {
log('Injecting custom scripts to index.html');
return gulp
.src(config.index)
.pipe( $.inject(gulp.src(config.js), {relative: true}) )
.pipe(gulp.dest(config.client));
});
gulp.task('copy', ['sass-min'], function() {
log('Copying assets');
var assets = [].concat(config.assetsLazyLoad, config.assetsToCopy);
gulp.src(config.tmp + '/styles/loader.css').pipe(gulp.dest(config.dist + '/styles'));
return gulp
.src(assets, {base: config.client})
.pipe(gulp.dest(config.dist + '/'));
});
gulp.task('optimize', ['inject', 'sass-min'], function() {
log('Optimizing the js, css, html');
return gulp
.src(config.index)
.pipe($.plumber({errorHandler: swallowError}))
.pipe($.useref())
.pipe($.if('scripts/app.js', $.uglify()))
.pipe(gulp.dest( config.dist ));
});
gulp.task('serve', ['inject', 'sass'], function() {
startBrowserSync('serve');
});
gulp.task('build', ['optimize', 'copy'], function() {
startBrowserSync('dist');
})
gulp.task('serve-dist', function() {
gulp.run('build');
})
gulp.task('serve-docs', ['pug-docs'], function() {
startBrowserSync('docs');
})
function clean(path, done) {
log('Cleaning: ' + $.util.colors.blue(path));
del(path, done);
}
function log(msg) {
if (typeof(msg) === 'object') {
for (var item in msg) {
if (msg.hasOwnProperty(item)) {
$.util.log($.util.colors.green(msg[item]));
}
}
} else {
$.util.log($.util.colors.green(msg));
}
}
function swallowError (error) {
// If you want details of the error in the console
console.log(error.toString());
this.emit('end');
}
function startBrowserSync(opt) {
if (args.nosync || browserSync.active) {
return;
}
var options = {
port: 3000,
ghostMode: {
clicks: false,
location: false,
forms: false,
scroll: true
},
injectChanges: true,
logFileChanges: true,
logLevel: 'debug',
logPrefix: 'gulp-patterns',
notify: true,
reloadDelay: 0, //1000,
online: false
};
switch(opt) {
case 'dist':
log('Serving dist app');
serveDistApp();
break;
case 'docs':
log('Serving docs');
serveDocs();
break;
default:
log('Serving app');
serveApp();
break;
}
function serveApp() {
gulp.watch([config.sass], ['sass']);
options.server = {
baseDir: [
config.client,
config.tmp
]
};
options.files = [
config.client + '/**/*.*',
'!' + config.sass,
config.tmp + '/**/*.css'
];
browserSync(options);
}
function serveDistApp() {
options.server = {
baseDir: [
config.dist
]
};
options.files = [];
browserSync(options);
}
function serveDocs() {
gulp.watch([config.docsPug], ['pug-docs']);
options.server = {
baseDir: [
config.docs
]
}
options.files = [
config.docs + '/index.html',
'!' + config.pug
];
browserSync(options);
}
}
I just run into the same problem while upgrading to gulp 4.
The depending tasks have to be specified as series or in parallel, just the name is not enough anymore.
Example
gulp.task('copy', ['sass-min'], function() {
Becomes
gulp.task('copy', gulp.series('sass-min'), function() {
gulp.parallel can also be used to execute the tasks in parallel
I had this exact problem with Gulp and it turns out that you must do away with tasks like that.
You must define your tasks as simple functions and then use your functions to define a task with gulp.series() or gulp.parallel().
I don't use this on Angular, but here's my gulpfile:
const bsync = require('browser-sync');
const gulp = require('gulp');
const autoprefixer = require('gulp-autoprefixer');
const sass = require('gulp-sass');
function sync(done) {
bsync.init({
files: [
'*.html',
'assets/css/**/*.css',
'assets/js/**/*.js'
],
host: '0.0.0.0',
server: './',
port: 8080,
reloadDelay: 1000,
ghostMode: false,
notify: false
});
done();
}
function styles() {
return gulp.src('./assets/scss/**/*.scss')
.pipe(sass({ outputStyle: 'expanded' }).on('error', sass.logError))
.pipe(autoprefixer({ remove: false }))
.pipe(gulp.dest('./assets/css'))
.pipe(bsync.stream());
}
function watchFiles() {
gulp.watch('./assets/scss/**/*.scss', styles);
}
gulp.task('start', gulp.series(sync, styles, watchFiles));
I've got inspired by this example. Hope it helps.
This is my gulpfile.js
var gulp = require('gulp');
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');
var livereload = require('gulp-livereload');
var del = require('del');
var minifyCss = require('gulp-minify-css');
var autoprefixer = require('gulp-autoprefixer');
var rename = require('gulp-rename');
var htmlmin = require('gulp-htmlmin');
var ngAnnotate = require('gulp-ng-annotate');
var sourcemaps = require('gulp-sourcemaps');
var paths = {
html: {entry: ['public/angular/entry.html'], partials: ['public/angular/partials/**/*.html'], views: ['public/angular/views/**/*.html']},
dist: 'public/dist',
bower_components: ['bower_components/jquery/dist/jquery.min.js', 'bower_components/jquery.cookie/jquery.cookie.js', 'bower_components/bootstrap/dist/js/bootstrap.min.js', 'bower_components/jquery.nicescroll/jquery.nicescroll.min.js','bower_components/jquery-sparkline/dist/jquery.sparkline.min.js', 'bower_components/jquery.easing/jquery.easing.min.js', 'bower_components/bootbox.js/bootbox.js', 'bower_components/retina.js/dist/retina.min.js', 'bower_components/angular/angular.min.js', 'bower_components/angular-sanitize/angular-sanitize.min.js', 'bower_components/angular-touch/angular-touch.min.js', 'bower_components/angular-animate/angular-animate.min.js', 'bower_components/angular-bootstrap/ui-bootstrap-tpls.min.js', 'bower_components/oclazyload/dist/ocLazyLoad.min.js', 'bower_components/angular-ui-router/release/angular-ui-router.min.js', 'bower_components/angular-ui-router/release/stateEvents.min.js', 'bower_components/angular-loading-bar/build/loading-bar.min.js', 'bower_components/angular-ui-select/dist/select.js', 'bower_components/checklist-model/checklist-model.js'],
app_scripts: ['public/angular/scripts/app.js', 'public/angular/scripts/**/*.js'],
app_styles: ['public/angular/styles/reset.css', 'public/angular/styles/layout.css', 'public/angular/styles/components.css', 'public/angular/styles/plugins.css', 'public/angular/styles/themes/green-army.theme.css', 'public/angular/styles/custom.css', 'public/angular/styles/layout/header-loggedin.css', 'public/angular/styles/layout/header-loggedout.css', 'public/angular/styles/pages/sign-in.css', 'public/angular/styles/pages/pos.css', 'public/angular/styles/pages/brand.css', 'public/angular/styles/pages/products.css', 'public/angular/styles/pages/pricing.css', 'public/angular/styles/pages/landing-page.css', 'public/angular/styles/pages/company-profile.css', 'public/angular/styles/invoice-print.css', 'public/angular/styles/angular-custom.css'],
bower_components_styles: ['bower_components/bootstrap/dist/css/bootstrap.min.css', 'bower_components/font-awesome/css/font-awesome.min.css', 'bower_components/animate.css/animate.min.css', 'bower_components/angular-loading-bar/build/loading-bar.min.css', 'bower_components/angular-ui-select/dist/select.min.css', 'bower_components/angular-ui-select/dist/select.css', 'bower_components/angular-bootstrap/ui-bootstrap-csp.css']
};
gulp.task('clean', function () {
return del.sync([paths.dist]);
});
gulp.task('html', ['mainHtml', 'partialsHtml', 'viewsHtml'], function() {
console.log('copying html files started');
});
gulp.task('mainHtml', function() {
gulp.src(paths.html.entry)
.pipe(htmlmin({collapseWhitespace: true}))
.pipe(rename('index.html'))
.pipe(gulp.dest(paths.dist));
});
gulp.task('partialsHtml', function() {
gulp.src(paths.html.partials)
.pipe(htmlmin({collapseWhitespace: true}))
.pipe(gulp.dest(paths.dist + '/partials'));
});
gulp.task('viewsHtml', function() {
gulp.src(paths.html.views)
.pipe(htmlmin({collapseWhitespace: true}))
.pipe(gulp.dest(paths.dist + '/views'));
});
gulp.task('styles', ['bower-styles', 'app-styles'], function(){
console.log('starting styles task');
})
gulp.task('bower-styles', function(){
return gulp.src(paths.bower_components_styles)
.pipe(autoprefixer())
.pipe(concat('bower_styles.css'))
.pipe(minifyCss())
.pipe(gulp.dest(paths.dist))
})
gulp.task('fonts', function() {
return gulp.src(['bower_components/font-awesome/fonts/fontawesome-webfont.*'])
.pipe(gulp.dest('public/dist/fonts/'));
});
gulp.task('app-styles', function(){
return gulp.src(paths.app_styles)
.pipe(autoprefixer())
.pipe(concat('app_styles.css'))
.pipe(minifyCss())
.pipe(gulp.dest(paths.dist))
})
gulp.task('scripts', ['bower_scripts','app_scripts'], function(){
console.log('starting scripts task');
})
gulp.task('bower_scripts', function(){
console.log('starting bower scripts task');
return gulp.src(paths.bower_components)
.pipe(sourcemaps.init())
.pipe(ngAnnotate())
.pipe(uglify({mangle:false}))
.pipe(concat('bower_scripts.js'))
.pipe(sourcemaps.write())
.pipe(gulp.dest(paths.dist))
})
gulp.task('app_scripts', function(){
console.log('starting app scripts task');
return gulp.src(paths.app_scripts)
.pipe(sourcemaps.init())
.pipe(ngAnnotate())
.pipe(uglify({mangle:false}))
.pipe(concat('app_scripts.js'))
.pipe(sourcemaps.write())
.pipe(gulp.dest(paths.dist))
})
gulp.task('default', ['clean', 'html', 'styles', 'fonts', 'scripts'], function(){
console.log('starting default task');
})
This is the output generated for the particular controller
"use strict";angular.module("sbApp").controller("BrandsCtrl",["$scope","$rootScope","$state","CustomStorage","Brands","$uibModalStack",function($scope,$rootScope,$state,CustomStorage,Brands,$uibModalStack){$scope.vm={brand:{title:"",description:""}},$scope.createBrand=function(){return $scope.vm.errorMsg="",$scope.vm.successMsg="",""==$scope.vm.brand.title||null==$scope.vm.brand.title||void 0==$scope.vm.brand.title||$scope.vm.brand.title.length<3||$scope.vm.brand.title.length>30?$scope.vm.errorMsg="The title must be min 3 max 30 letters":""==$scope.vm.brand.description||null==$scope.vm.brand.description||void 0==$scope.vm.brand.description?$scope.vm.errorMsg="Description is required":$scope.vm.brand.description.length<3||$scope.vm.brand.description.length>1e3?$scope.vm.errorMsg="Description must be min 3 max 1000 letters.":($scope.displaySpinner=!0,void Brands.addNew($scope.vm.brand).then(function(response){$scope.vm.brand.title="",$scope.vm.brand.description="",$scope.vm.successMsg=response.data.title+" added successfully."},function(err){$scope.vm.errorMsg=err.data.message?err.data.message:err.data.msg})["finally"](function(){$scope.displaySpinner=!1}))},$scope.disposeModal=function(){$uibModalStack.dismissAll()}}]);
I am getting error for ui.bootstrap modules, angular.min.js:123
Error:
[$injector:unpr]
http://errors.angularjs.org/1.6.4/$injector/unpr?p0=%24uibModalStackProvider%20%3C-%20%24uibModalStack%20%3C-%20InvoiceCtrl%20%3C-%20BrandsCtrl
I have already used gulp-ng-annotate,.pipe(uglify({mangle:false})) in mu gulpfile.js. Please suggest where it is breaking my app for $uibModal and why?
angular version - AngularJS v1.6.4
Node
It seems that you should add dependency on ui.bootstrap module:
angular.module("sbApp", ["ui.bootstrap"])...
It was duplicate files present and concat was actually adding same file twice
We have some code in Angular JS which is build using gulp (babel).
We have necessity to redirect the api service calls to a different server.
Hence, which development we run gulp server and with that add the api-host server in the proxy argument while running gulp server, as follows:
gulp serve:dist --mock no --proxy http://<host-name>:8090
Now, after development, we build and distribute the same bundle to different host (not the same host where the api services are hosted). Now we are not able to connect to the api server. The command we use to build is
gulp build:dist --mock no
Even if we add the proxy argument here, it doesn't works.
gulp build:dist --mock no --proxy http://<host-name>:8090
We tried customizing the "gulpfile.babel.js" file. but no result.
The following is the "gulpfile.babel.js" used:
'use strict';
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var runSequence = require('run-sequence');
var del = require('del');
var _ = require('lodash');
var historyApiFallback = require('connect-history-api-fallback');
var path = require('path');
var args = require('yargs').argv;
var proxyMiddleware = require('http-proxy-middleware');
var merge = require('merge-stream');
// browserSync
var browserSync = require('browser-sync');
var reload = browserSync.reload;
// config & testing
var config = require('./build/build.config.js');
var protractorConfig = require('./build/protractor.config.js');
var karmaConfig = require('./build/karma.config.js');
var KarmaServer = require('karma').Server;
var pkg = require('./package');
/* jshint camelcase:false*/
var webdriverStandalone = require('gulp-protractor').webdriver_standalone;
var webdriverUpdate = require('gulp-protractor').webdriver_update;
//update webdriver if necessary, this task will be used by e2e task
gulp.task('webdriver:update', webdriverUpdate);
// util functions
function sortModulesFirst(a, b) {
var module = /\.module\.js$/;
var aMod = module.test(a.path);
var bMod = module.test(b.path);
// inject *.module.js first
if (aMod === bMod) {
// either both modules or both non-modules, so just sort normally
if (a.path < b.path) {
return -1;
}
if (a.path > b.path) {
return 1;
}
return 0;
} else {
return (aMod ? -1 : 1);
}
}
// serve app in dev mode or prod mode
function serverOptions(logPrefix) {
var proxy = args.proxy;
var options = {
notify: false,
logPrefix: pkg.name,
server: {
baseDir: ['build', 'client']
}
};
// use a proxy server to serve '/api/**'' and '/auth' routes
if (proxy && args.mock === 'no') {
options.server.middleware = [
proxyMiddleware(['/auth', '/api'], {
target: proxy
}),
historyApiFallback()
];
} else {
// use Angular's $httpBackend as the server
options.server.middleware = [
historyApiFallback()
];
}
if (logPrefix) {
options.logPrefix = pkg.name;
}
return options;
}
// run unit tests and watch files
gulp.task('tdd', function(cb) {
new KarmaServer(_.assign({}, karmaConfig, {
singleRun: false,
action: 'watch',
browsers: ['PhantomJS']
}), cb).start();
});
// run unit tests with travis CI
gulp.task('travis', ['build'], function(cb) {
new KarmaServer(_.assign({}, karmaConfig, {
singleRun: true,
browsers: ['PhantomJS']
}), cb).start();
});
// optimize images and put them in the dist folder
gulp.task('images', function() {
return gulp.src(config.images, {
base: config.base
})
.pipe($.imagemin({
progressive: true,
interlaced: true
}))
.pipe(gulp.dest(config.dist))
.pipe($.size({
title: 'images'
}));
});
//generate angular templates using html2js
gulp.task('templates', function() {
return gulp.src(config.tpl)
.pipe($.changed(config.tmp))
.pipe($.html2js({
outputModuleName: 'templates',
base: 'client',
useStrict: true
}))
.pipe($.concat('templates.js'))
.pipe(gulp.dest(config.tmp))
.pipe($.size({
title: 'templates'
}));
});
//generate css files from scss sources
gulp.task('sass', function() {
return gulp.src(config.mainScss)
.pipe($.sass())
.pipe($.autoprefixer({
browsers: ['last 2 versions'],
cascade: false
}))
.on('error', $.sass.logError)
.pipe(gulp.dest(config.tmp))
.pipe($.size({
title: 'sass'
}));
});
//generate a minified css files, 2 js file, change theirs name to be unique, and generate sourcemaps
gulp.task('html', function() {
let useminConfig = {
path: '{build,client}',
css: [$.csso(), $.rev()],
vendorJs: [$.uglify({
mangle: false
}), $.rev()],
mainJs: [$.ngAnnotate(), $.uglify({
mangle: false
}), $.rev()]
};
if (args.mock === 'no') {
// Don't include mock vendor js
useminConfig.mockVendorJs = [];
return gulp.src(config.index)
.pipe($.usemin(useminConfig))
.pipe($.replace('<script src="assets/js/mock-vendor.js"></script>', ''))
.pipe(gulp.dest(config.dist))
.pipe($.size({
title: 'html'
}));
} else {
// Include mock vendor js
useminConfig.mockVendorJs = [$.uglify({
mangle: false
}), $.rev()];
return gulp.src(config.index)
.pipe($.usemin(useminConfig))
.pipe(gulp.dest(config.dist))
.pipe($.size({
title: 'html'
}));
}
});
// clean up mock vendor js
gulp.task('clean:mock', function(cb) {
if (args.mock === 'no') {
let paths = [path.join(config.dist, 'assets/js/mock-vendor.js')];
del(paths).then(() => {
cb();
});
} else {
cb();
}
});
//copy assets in dist folder
gulp.task('copy:assets', function() {
return gulp.src(config.assets, {
dot: true,
base: config.base
})
//.pipe(gulp.dest(config.dist + '/assets'))
.pipe(gulp.dest(config.dist))
.pipe($.size({
title: 'copy:assets'
}));
});
//copy assets in dist folder
gulp.task('copy', function() {
return gulp.src([
config.base + '/*',
'!' + config.base + '/*.html',
'!' + config.base + '/src',
'!' + config.base + '/test',
'!' + config.base + '/bower_components'
])
.pipe(gulp.dest(config.dist))
.pipe($.size({
title: 'copy'
}));
});
//clean temporary directories
gulp.task('clean', del.bind(null, [config.dist, config.tmp]));
//lint files
gulp.task('jshint', function() {
return gulp.src(config.js)
.pipe(reload({
stream: true,
once: true
}))
.pipe($.jshint())
.pipe($.jshint.reporter('jshint-stylish'))
.pipe($.if(!browserSync.active, $.jshint.reporter('fail')));
});
// babel
gulp.task('transpile', function() {
return gulp.src(config.js)
.pipe($.sourcemaps.init())
.pipe($.babel({
presets: ['es2015']
}))
.pipe($.sourcemaps.write('.'))
.pipe(gulp.dest(
path.join(config.tmp, 'src')
));
});
// inject js
gulp.task('inject:js', () => {
var injectJs = args.mock === 'no' ?
config.injectJs :
config.injectJs.concat(config.mockJS);
return gulp.src(config.index)
.pipe($.inject(
gulp
.src(injectJs, {
read: false
})
.pipe($.sort(sortModulesFirst)), {
starttag: '<!-- injector:js -->',
endtag: '<!-- endinjector -->',
transform: (filepath) => '<script src="' + filepath.replace('/client', 'tmp') + '"></script>'
}))
.pipe(gulp.dest(config.base));
});
/** ===================================
build tasks
======================================*/
//build files for development
gulp.task('build', ['clean'], function(cb) {
runSequence(['sass', 'templates', 'transpile', 'inject:js'], cb);
});
//build files for creating a dist release
gulp.task('build:dist', ['clean'], function(cb) {
//runSequence(['jshint', 'build', 'copy', 'copy:assets', 'images', 'test:unit'], 'html', cb);
runSequence(['jshint', 'build', 'copy', 'copy:assets', 'images'], 'html', 'clean:mock', cb);
});
// For aniden internal usage
// changed app root for labs server
gulp.task('labs:aniden', function() {
let base = `/hpe/mvno_portal/build/v${pkg.version}/`;
let html = gulp.src(config.dist + '/index.html', {
base: config.dist
})
.pipe($.replace('<base href="/">', `<base href="${base}">`))
.pipe(gulp.dest(config.dist));
let css = gulp.src(config.dist + '/**/*.css', {
base: config.dist
})
.pipe($.replace('url(/', `url(${base}`))
.pipe($.replace('url("/', `url("${base}`))
.pipe(gulp.dest(config.dist));
let js = gulp.src(config.dist + '/**/*.js', {
base: config.dist
})
.pipe($.replace('href="/"', `href="${base}"`))
.pipe(gulp.dest(config.dist));
return merge(html, css, js);
});
/** ===================================
tasks supposed to be public
======================================*/
//default task
gulp.task('default', ['serve']); //
//run unit tests and exit
gulp.task('test:unit', ['build'], function(cb) {
new KarmaServer(_.assign({}, karmaConfig, {
singleRun: true
}), cb).start();
});
// Run e2e tests using protractor, make sure serve task is running.
gulp.task('test:e2e', ['webdriver:update'], function() {
return gulp.src(protractorConfig.config.specs)
.pipe($.protractor.protractor({
configFile: 'build/protractor.config.js'
}))
.on('error', function(e) {
throw e;
});
});
//run the server, watch for file changes and redo tests.
gulp.task('serve:tdd', function(cb) {
runSequence(['serve', 'tdd'], cb);
});
//run the server after having built generated files, and watch for changes
gulp.task('serve', ['build'], function() {
browserSync(serverOptions());
gulp.watch(config.html, reload);
gulp.watch(config.scss, ['sass', reload]);
gulp.watch(config.js, ['jshint', 'transpile']);
gulp.watch(config.tpl, ['templates', reload]);
gulp.watch(config.assets, reload);
});
//run the app packed in the dist folder
gulp.task('serve:dist', ['build:dist'], function() {
browserSync(serverOptions());
});
You can use gulp-ng-config to add constant in you app module.
Or you a JSON as a config file inside your gulp:
//Gulp file
var fs = require('fs');
var settings = JSON.parse(fs.readFileSync('./config/config.json', 'utf8'));
....
gulp.task('statics', g.serve({
port: settings.frontend.ports.development,
...
}));
gulp.task('production', g.serve({
port: settings.frontend.ports.production,
root: ['./dist'],
...
}));
I have a directory that I am putting my Angular Partials into. Containing these files:
➜ partials: pwd
/home/dev/webapp/ui/public/partials
➜ partials: ls
connect-local.html landing.html login.html profile.html signup.html
And I am running gulp to concat and minify them into Angulars Template Cache. I have this in my gulpfile
//gulpfile.js
...
.pipe(plugins.usemin({
templateCache: [
gulp.src(['public/partials/*.html']),
plugins.debug(),
plugins.angularTemplatecache({
module: 'myApp',
root: 'partials/'
}),
'concat',
plugins.rev()
]
})))
.pipe(gulp.dest('dist/'));
However the gulp.src is only picking up some of my files as shown by gulp-debug:
[15:46:53] Starting 'build'...
[15:46:55] gulp-debug: ~/what/ui/public/partials/connect-local.html
[15:46:55] gulp-debug: ~/what/ui/public/partials/landing.html
[15:46:55] gulp-debug: ~/what/ui/public/partials/login.html
[15:46:55] gulp-debug: ~/what/ui/public/assets/javascript/templates.js
[15:46:55] gulp-debug: 4 items
[15:46:55] Finished 'build' after 1.29 s
Is there something I am missing? I have used this code before successfully. Is there a workaround? Its kinda crippling my application atm
Here is my gulp build so you can compare to see if it helps to find what you are missing:
'use strict';
var gulp = require('gulp');
var $ = require('gulp-load-plugins')({
pattern: ['gulp-*', 'main-bower-files', 'uglify-save-license', 'del']
});
module.exports = function(options) {
gulp.task('partials', function () {
return gulp.src([
options.src + '/{app,components}/**/*.html',
options.tmp + '/serve/{app,components}/**/*.html'
])
.pipe($.minifyHtml({
empty: true,
spare: true,
quotes: true
}))
.pipe($.angularTemplatecache('templateCacheHtml.js', {
module: 'myApp',
root: '/'
}))
.pipe(gulp.dest(options.tmp + '/partials/'));
});
gulp.task('html', ['inject', 'partials'], function () {
var partialsInjectFile = gulp.src(options.tmp + '/partials/templateCacheHtml.js', { read: false });
var partialsInjectOptions = {
starttag: '<!-- inject:partials -->',
ignorePath: options.tmp + '/partials',
addRootSlash: false
};
var htmlFilter = $.filter('*.html');
var jsFilter = $.filter('**/*.js');
var cssFilter = $.filter('**/*.css');
var assets;
return gulp.src(options.tmp + '/serve/*.html')
.pipe($.inject(partialsInjectFile, partialsInjectOptions))
.pipe(assets = $.useref.assets())
.pipe($.rev())
.pipe(jsFilter)
.pipe($.ngAnnotate())
.pipe($.uglify({ preserveComments: $.uglifySaveLicense })).on('error', options.errorHandler('Uglify'))
.pipe(jsFilter.restore())
.pipe(cssFilter)
.pipe($.replace('../../bower_components/bootstrap/fonts/', '../fonts/'))
.pipe($.csso())
.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(options.dist + '/'))
.pipe($.size({ title: options.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(options.dist + '/fonts/'));
});
gulp.task('other', function () {
return gulp.src([
options.src + '/**/*.*',
'!' + options.src + '/**/*.{html,css,js,less}'
])
.pipe(gulp.dest(options.dist + '/'));
});
gulp.task('clean', function (done) {
$.del([options.dist + '/', options.tmp + '/'], done);
});
gulp.task('build', ['html', 'fonts', 'other']);
gulp.task('build:clean',['clean'],function(){
gulp.start('build');
});
};