Gulp-ruby-sass Error : - javascript

The gulp plugin gulp-ruby-sass doesn't work when compiling sass files .
'use strict';
var path = require('path');
var gulp = require('gulp');
var conf = require('./conf');
var browserSync = require('browser-sync');
var $ = require('gulp-load-plugins')();
var wiredep = require('wiredep').stream;
var _ = require('lodash');
gulp.task('styles-reload', ['styles'], function() {
return buildStyles()
.pipe(browserSync.stream());
});
gulp.task('styles', function() {
return buildStyles();
});
var buildStyles = function() {
var sassOptions = {
style: 'expanded'
};
var injectFiles = gulp.src([
path.join(conf.paths.src, '/app/**/*.scss'),
path.join('!' + conf.paths.src, '/app/index.scss')
], { read: false });
var injectOptions = {
transform: function(filePath) {
filePath = filePath.replace(conf.paths.src + '/app/', '');
return '#import "' + filePath + '";';
},
starttag: '// injector',
endtag: '// endinjector',
addRootSlash: false
};
var cssFilter = $.filter('**/*.css', { restore: true });
return gulp.src([
path.join(conf.paths.src, '/app/index.scss')
])
.pipe($.inject(injectFiles, injectOptions))
.pipe(wiredep(_.extend({}, conf.wiredep)))
.pipe($.rubySass(sassOptions)).on('error', conf.errorHandler('RubySass'))
.pipe(cssFilter)
.pipe($.sourcemaps.init({ loadMaps: true }))
.pipe($.autoprefixer()).on('error', conf.errorHandler('Autoprefixer'))
.pipe($.sourcemaps.write())
.pipe(cssFilter.restore)
.pipe(gulp.dest(path.join(conf.paths.tmp, '/serve/app/')));
};
TypeError: glob pattern string required
at new Minimatch (/home/john/sac_srvs/new_srvs/sachin/node_modules/gulp-ruby-sass/node_modules/glob/node_modules/minimatch/minimatch.js:108:11)
at setopts (/home/john/sac_srvs/new_srvs/sachin/node_modules/gulp-ruby-sass/node_modules/glob/common.js:112:20)
at new GlobSync (/home/john/sac_srvs/new_srvs/sachin/node_modules/gulp-ruby-sass/node_modules/glob/sync.js:38:3)
at Function.globSync [as sync] (/home/john/sac_srvs/new_srvs/sachin/node_modules/gulp-ruby-sass/node_modules/glob/sync.js:24:10)
at /home/john/sac_srvs/new_srvs/sachin/node_modules/gulp-ruby-sass/index.js:68:21
at Array.forEach (native)
at Object.gulpRubySass (/home/john/sac_srvs/new_srvs/sachin/node_modules/gulp-ruby-sass/index.js:67:10)
at buildStyles (/home/john/sac_srvs/new_srvs/sachin/gulp/styles.js:50:13)
at Gulp.sassOptions.style (/home/john/sac_srvs/new_srvs/sachin/gulp/styles.js:20:10)
at module.exports (/home/john/sac_srvs/new_srvs/sachin/node_modules/gulp/node_modules/orchestrator/lib/runTask.js:34:7)
at Gulp.Orchestrator._runTask (/home/john/sac_srvs/new_srvs/sachin/node_modules/gulp/node_modules/orchestrator/index.js:273:3)
at Gulp.Orchestrator._runStep (/home/john/sac_srvs/new_srvs/sachin/node_modules/gulp/node_modules/orchestrator/index.js:214:10)
at Gulp.Orchestrator.start (/home/john/sac_srvs/new_srvs/sachin/node_modules/gulp/node_modules/orchestrator/index.js:134:8)
at /usr/local/lib/node_modules/gulp/bin/gulp.js:129:20
at process._tickCallback (node.js:415:13)
at Function.Module.runMain (module.js:499:11)

This is a tricky one. Looks like you're using generator-gulp-angular and selected ruby-sass. Unfortunately, the API of gulp-ruby-sass has changed in September (with their 2.0.0 release) and the generator wasn't updated since. In a nutshell: the new API needs the source files passed into the stream factory method
.pipe($.rubySass([**SOURCE FILES HERE**], sassOptions)).on('error', conf.errorHandler('RubySass'))
which is basically not possible when combining the build chain with other plugins like inject or wiredep.
My recommendation is to use node-sass instead - if you have no absolute need for ruby-sass of course.

Related

AssertionError while using gulp. 'Task function must be specified'

I'm trying to use Gulp as part of a React tutorial I'm walking through. After installing the dependencies I've been given;
AssertionError [ERR_ASSERTION]: Task function must be specified
This is the gulpfile.js which I am using
'use strict';
// dependencies
var gulp = require('gulp');
var sass = require('gulp-sass');
var minifyCSS = require('gulp-clean-css');
var uglify = require('gulp-uglify');
var renamed = require('gulp-rename');
var changed = require('gulp-changed');
// - SCSS/CSS
var SCSS_SRC = './src/Assets/scss/**/*.scss';
var SCSS_DEST = './src/Assets/css';
// Compile SCSS
gulp.task('compile_scss', function(){
gulp.src(SCSS_SRC)
.pipe(sass().on('error', sass.logError))
.pipe(minifyCSS())
.pipe(rename({ suffix: '.min' }))
.pipe(changed(SCSS_DEST))
.pipe(gulp.dest(SCSS_DEST));
});
// detect changes in SCSS
gulp.task('watch_scss', function(){
gulp.watch(SCSS_SRC, ['compile_scss']);
});
// Run tasks
gulp.task('default', ['watch_scss']);
And this outputs the following messages
generatedMessage: false,
code: 'ERR_ASSERTION',
actual: false,
expected: true,
operator: '=='
The tutorial I am using was made in April 2017. Could it be something to do with conflicting versions?
Any help is appreciated.
The problem was I was using v3 gulp, the problem was solved by upgrading to v4.
The code is below.
'use strict';
// dependencies
var gulp = require('gulp');
var sass = require('gulp-sass');
var minifyCSS = require('gulp-clean-css');
var uglify = require('gulp-uglify');
var renamed = require('gulp-rename');
var changed = require('gulp-changed');
// - SCSS/CSS
var SCSS_SRC = './src/Assets/scss/**/*.scss';
var SCSS_DEST = './src/Assets/css';
function compile_scss (done) {
gulp.src(SCSS_SRC)
.pipe(sass().on('error', sass.logError))
.pipe(minifyCSS())
.pipe(renamed({ suffix: '.min' }))
.pipe(changed(SCSS_DEST))
.pipe(gulp.dest(SCSS_DEST));
done();
}
// detect changes in SCSS
function detect_change_scss (done) {
gulp.watch(SCSS_SRC)
done();
}
// Run tasks
gulp.task("compile_scss", gulp.series(compile_scss, detect_change_scss, ));

TypeError: $.useref.assets is not a function

I'm trying to build an Angular app using heroku, I keep getting this error whenever it reaches the html build state. It's my first time deploying to heroku but over the past few days I've kept getting different errors while the app runs without any problem on my local machine, and on a server.
TypeError: $.useref.assets is not a function
2017-04-18T14:36:18.895917+00:00 app[web.1]: at Gulp.<anonymous> (/app/gulpfile.js:55:25)
2017-04-18T14:36:18.895918+00:00 app[web.1]: at module.exports (/app/node_modules/orchestrator/lib/runTask.js:34:7)
2017-04-18T14:36:18.895919+00:00 app[web.1]: at Gulp.Orchestrator._runTask (/app/node_modules/orchestrator/index.js:273:3)
2017-04-18T14:36:18.895920+00:00 app[web.1]: at Gulp.Orchestrator._runStep (/app/node_modules/orchestrator/index.js:214:10)
2017-04-18T14:36:18.895920+00:00 app[web.1]: at /app/node_modules/orchestrator/index.js:279:18
2017-04-18T14:36:18.895921+00:00 app[web.1]: at finish (/app/node_modules/orchestrator/lib/runTask.js:21:8)
2017-04-18T14:36:18.895922+00:00 app[web.1]: at /app/node_modules/orchestrator/lib/runTask.js:52:4
2017-04-18T14:36:18.895922+00:00 app[web.1]: at f (/app/node_modules/end-of-stream/node_modules/once/once.js:17:25)
2017-04-18T14:36:18.895923+00:00 app[web.1]: at DestroyableTransform.onend (/app/node_modules/end-of-stream/index.js:31:18)
2017-04-18T14:36:18.895924+00:00 app[web.1]: at emitNone (events.js:91:20)
2017-04-18T14:36:18.895924+00:00 app[web.1]: at DestroyableTransform.emit (events.js:185:7)
2017-04-18T14:36:18.895925+00:00 app[web.1]: at /app/node_modules/vinyl-fs/node_modules/readable-stream/lib/_stream_readable.js:965:16
2017-04-18T14:36:18.895925+00:00 app[web.1]: at _combinedTickCallback (internal/process/next_tick.js:73:7)
2017-04-18T14:36:18.895926+00:00 app[web.1]: at process._tickCallback (internal/process/next_tick.js:104:9)
This is my gulpfile.js
/* jshint node:true */
'use strict';
var gulp = require('gulp');
var karma = require('karma').server;
var argv = require('yargs').argv;
var $ = require('gulp-load-plugins')();
var gulp = require('gulp'),
useref = require('gulp-useref');
gulp.task('styles', function() {
return gulp.src([
'app/styles/less/app-green.less',
'app/styles/less/app-blue.less',
'app/styles/less/app-red.less',
'app/styles/less/app-orange.less'
])
.pipe($.plumber())
.pipe($.less())
.pipe($.autoprefixer({browsers: ['last 1 version']}))
.pipe(gulp.dest('dist/styles'))
.pipe(gulp.dest('app/styles'))
.pipe(gulp.dest('.tmp/styles'));
});
gulp.task('html', function() {
return gulp.src(options.src + '/index.html')
.pipe(useref())
.pipe(gulpif('*.js', uglify()))
.pipe(gulp.dest(options.dist));
});''
gulp.task('jshint', function() {
return gulp.src('app/scripts/**/*.js')
.pipe($.jshint())
//.pipe($.jshint.reporter('jshint-stylish'))
//.pipe($.jshint.reporter('fail'));
});
gulp.task('jscs', function() {
return gulp.src('app/scripts/**/*.js')
.pipe($.jscs());
});
gulp.task('html', ['styles'], function() {
var lazypipe = require('lazypipe');
var cssChannel = lazypipe()
.pipe($.csso)
.pipe($.replace, 'bower_components/bootstrap/fonts', 'fonts');
var assets = useref.assets({searchPath: '{.tmp,app}'});
return gulp.src('app/**/*.html')
//.pipe(assets)
.pipe($.if('*.js', $.ngAnnotate()))
.pipe($.if('*.js', $.uglify()))
.pipe($.if('*.css', cssChannel()))
.pipe(useref())
pipe(assets.restore())
.pipe($.useref())
.pipe($.if('*.html', $.minifyHtml({conditionals: true, loose: true})))
.pipe(gulp.dest('dist'));
});
gulp.task('images', function() {
return gulp.src('app/images/**/*')
// .pipe($.cache($.imagemin({
// progressive: true,
// interlaced: true
// })))
.pipe(gulp.dest('dist/images'));
});
gulp.task('fonts', function() {
return gulp.src(require('main-bower-files')().concat('app/styles/fonts/**/*')
.concat('bower_components/bootstrap/fonts/*'))
.pipe($.filter('**/*.{eot,svg,ttf,woff,woff2}'))
.pipe($.flatten())
.pipe(gulp.dest('dist/fonts'))
.pipe(gulp.dest('app/fonts'))
.pipe(gulp.dest('.tmp/fonts'));
});
gulp.task('extras', function() {
return gulp.src([
'app/*.*',
'!app/*.html',
'node_modules/apache-server-configs/dist/.htaccess'
], {
dot: true
}).pipe(gulp.dest('dist'));
});
gulp.task('clean', require('del').bind(null, ['.tmp', 'dist']));
gulp.task('connect', ['styles'], function() {
var serveStatic = require('serve-static');
var serveIndex = require('serve-index');
var app = require('connect')()
.use(require('connect-livereload')({port: 35729}))
.use(serveStatic('.tmp'))
.use(serveStatic('app'))
// paths to bower_components should be relative to the current file
// e.g. in app/index.html you should use ../bower_components
.use('/bower_components', serveStatic('bower_components'))
.use(serveIndex('app'));
require('http').createServer(app)
.listen(9000)
.on('listening', function() {
console.log('Started connect web server on http://localhost:9000');
});
});
gulp.task('serve', ['wiredep', 'connect', 'fonts', 'watch'], function() {
if (argv.open) {
require('opn')('http://localhost:9000');
}
});
gulp.task('test', function(done) {
karma.start({
configFile: __dirname + '/test/karma.conf.js',
singleRun: true
}, done);
});
// inject bower components
gulp.task('wiredep', function() {
var wiredep = require('wiredep').stream;
var exclude = [
'bootstrap',
'jquery',
'es5-shim',
'json3',
'angular-scenario'
];
gulp.src('app/styles/*.less')
.pipe(wiredep())
.pipe(gulp.dest('app/styles'));
gulp.src('app/*.html')
.pipe(wiredep({exclude: exclude}))
.pipe(gulp.dest('app'));
gulp.src('test/*.js')
.pipe(wiredep({exclude: exclude, devDependencies: true}))
.pipe(gulp.dest('test'));
});
gulp.task('watch', ['connect'], function() {
$.livereload.listen();
// watch for changes
gulp.watch([
'app/**/*.html',
'.tmp/styles/**/*.css',
'app/scripts/**/*.js',
'app/images/**/*'
]).on('change', $.livereload.changed);
gulp.watch('app/styles/**/*.less', ['styles']);
gulp.watch('bower.json', ['wiredep']);
});
gulp.task('builddist', ['jshint', 'html', 'images', 'fonts', 'extras', 'styles'],
function() {
return gulp.src('dist/**/*').pipe($.size({title: 'build', gzip: true}));
});
gulp.task('build', ['clean'], function() {
gulp.start('builddist');
});
gulp.task('docs', [], function() {
return gulp.src('app/scripts/**/**')
.pipe($.ngdocs.process())
.pipe(gulp.dest('./docs'));
});
This was written before OP changed his question to include the content of this answer.
The error tells you that $.useref.assets is not a function and it comes from the following line:
var assets = $.useref.assets({searchPath: '{.tmp,app}'});
Since you're already loading the gulp-useref plugin into a local variable
var useref = require('gulp-useref'),
You don't need to use the $ of gulp-load-plugins.
After that, the first thing you see in the readme of gulp-useref:
What's new in 3.0?
Changes under the hood have made the code more efficient and
simplified the API. Since the API has changed, please observe the
usage examples below.
If you get errors like
TypeError: useref.assets is not a function
or
TypeError: $.useref.assets is not a function
please read the Migration Notes below.
And below is the Migration from v2 API:
For a simple configuration, you can replace this V2 code:
var gulp = require('gulp'),
useref = require('gulp-useref');
gulp.task('default', function () {
var assets = useref.assets();
return gulp.src('app/*.html')
.pipe(assets)
.pipe(assets.restore())
.pipe(useref())
.pipe(gulp.dest('dist'));
});
with this V3 code:
var gulp = require('gulp'),
useref = require('gulp-useref');
gulp.task('default', function () {
return gulp.src('app/*.html')
.pipe(useref())
.pipe(gulp.dest('dist'));
});
You do not need to call useref.assets(...) anymore. Just pipe to useref() like in the V3 example.
replace you codes
var assets = useref.assets({searchPath: '{.tmp,app}'});
return gulp.src('app/**/*.html')
//.pipe(assets)
.pipe($.if('*.js', $.ngAnnotate()))
.pipe($.if('*.js', $.uglify()))
.pipe($.if('*.css', cssChannel()))
.pipe(useref())
pipe(assets.restore()) //you missed a dot point here
.pipe($.useref())
.pipe($.if('*.html', $.minifyHtml({conditionals: true, loose: true})))
.pipe(gulp.dest('dist'));
});
with something like:
return gulp
.src('app/**/*.html')
.pipe($.useref())
.pipe($.if('*.js', $.ngAnnotate()))
.pipe($.if('*.js', $.uglify())) //to uglify js files
.pipe($.if('*.css', $.csso())) //to uglify css files
.pipe(gulp.dest('dist'));
or
var jsAppFilter = $.filter('**/app.js', { restore: true });
return gulp
.src(config.index)
.pipe($.useref())
.pipe(jsAppFilter) //only add annotations to your custom js files
.pipe($.ngAnnotate())
.pipe(jsAppFilter.restore)
.pipe($.if('*.js', $.uglify()))
.pipe($.if('*.css', $.csso()))
.pipe(gulp.dest('./build'));

Add tsconfig.json properties to Gulp task

I keep on getting that error about using something different than ES5 standards while compiling, simply because I just started using TS and I don't know how to include the tsconfig.json directly in my Gulp task autocompile.
error TS1056: Accessors are only available when targeting ECMAScript 5 and higher
Is it possible to add my tsconfig.json file properties directly into my Gulp pipe?
Current gulpfile.js
'use strict';
var gulp = require('gulp');
var ts = require('gulp-typescript');
var tsProject = ts.createProject('tsconfig.json'); // TypeScript config
var merge = require('merge2'); // TypeScript requirement
var sass = require('gulp-sass');
var browserSync = require('browser-sync').create();
var useref = require('gulp-useref');
var uglify = require('gulp-uglify');
var gulpIf = require('gulp-if');
var cssnano = require('gulp-cssnano');
var imagemin = require('gulp-imagemin');
var cache = require('gulp-cache');
var del = require('del');
var runSequence = require('run-sequence');
gulp.task('sass', function () {
return gulp.src('app/assets/scss/**/*.scss')
.pipe(sass()) // Using gulp-sass
.pipe(gulp.dest('app/assets/css'))
.pipe(browserSync.reload({
stream: true
}));
});
gulp.task('typescript', function () {
var tsResult = gulp.src('app/assets/typescript/**/*.ts')
.pipe(ts({
declaration: true
}));
return merge([
tsResult.dts.pipe(gulp.dest('app/assets/definitions')),
tsResult.js.pipe(gulp.dest('app/assets/js'))
]);
});
gulp.task('watch', ['browserSync', 'sass'], function () {
gulp.watch('app/assets/typescript/**/*.ts', ['typescript']);
gulp.watch('app/assets/scss/**/*.scss', ['sass']);
// Reloads the browser whenever HTML or JS files change
gulp.watch('app/**/*.html', browserSync.reload);
gulp.watch('app/assets/js/**/*.js', browserSync.reload);
});
gulp.task('browserSync', function () {
browserSync.init({
server: {
baseDir: 'app'
},
});
});
gulp.task('useref', function () {
return gulp.src('app/*.html')
.pipe(useref())
.pipe(gulpIf('*.js', uglify()))
// Minifies only if it's a CSS file
.pipe(gulpIf('*.css', cssnano()))
.pipe(gulp.dest('dist'));
});
gulp.task('images', function () {
return gulp.src('app/assets/img/**/*.+(png|jpg|jpeg|gif|svg)')
// Caching images that ran through imagemin
.pipe(cache(imagemin({
interlaced: true
})))
.pipe(gulp.dest('dist/assets/img'));
});
gulp.task('fonts', function () {
return gulp.src('app/assets/fonts/**/*')
.pipe(gulp.dest('dist/assets/fonts'));
});
gulp.task('clean:dist', function () {
return del.sync('dist');
});
gulp.task('build', function (callback) {
runSequence('clean:dist', ['sass', 'useref', 'images', 'fonts'],
callback
);
});
gulp.task('default', function (callback) {
runSequence(['sass', 'typescript', 'browserSync', 'watch'],
callback
);
// Typescript compiler
});
I would recommend you to use your tsconfig.json as the only source of the properties. To do this change how you create tsResult:
var tsProject = ts.createProject('tsconfig.json');
var tsResult = tsProject.src().
.pipe(//....
Below is the complete task that works for me:
gulp.task('build.js.dev', () =>
{
var tsProject = ts.createProject('tsconfig.json');
var tsResult = tsProject.src()
.pipe(sourcemaps.init())
.pipe(tsProject());
return merge([
//Write definitions
//tsResult.dts.pipe(gulp.dest(TEMP_TARGET_FOLDER)),
//Write compiled js
tsResult.js.pipe(sourcemaps.write(
".",
{
includeContent: true,
sourceRoot: __dirname + "/dist"
})).pipe(gulp.dest(TEMP_TARGET_FOLDER))]);
});
The error you are getting is due to the fact that if you omit target compiler option the typescript compiler will fallback to ES3.

Gulp bower:scss not working including bower_components files

I have an issue with wiredep: In my index.scss file, I have this block at the top:
/**
* Do not remove this comments bellow. It's the markers used by wiredep to inject
* sass dependencies when defined in the bower.json of your dependencies
*/
// bower:scss
// endbower
Also, I have installed a bower dependency, let's say color-dependency, which contains a couple files *.scss
The problem is that I can't see those files injected in my index.scss
Here is my gulp task for styles
'use strict';
var path = require('path');
var gulp = require('gulp');
var conf = require('./conf');
var browserSync = require('browser-sync');
var $ = require('gulp-load-plugins')();
var wiredep = require('wiredep').stream;
var _ = require('lodash');
gulp.task('styles', function () {
var sassOptions = {
style: 'expanded'
};
var injectFiles = gulp.src([
path.join(conf.paths.src, '/app/**/*.scss'),
path.join('!' + conf.paths.src, '/app/index.scss')
], { read: false });
var injectOptions = {
transform: function(filePath) {
filePath = filePath.replace(conf.paths.src + '/app/', '');
return '#import "' + filePath + '";';
},
starttag: '// injector',
endtag: '// endinjector',
addRootSlash: false
};
return gulp.src([
path.join(conf.paths.src, '/app/index.scss')
])
.pipe($.inject(injectFiles, injectOptions))
.pipe(wiredep(_.extend({}, conf.wiredep)))
.pipe($.sourcemaps.init())
.pipe($.sass(sassOptions)).on('error', conf.errorHandler('Sass'))
.pipe($.autoprefixer()).on('error', conf.errorHandler('Autoprefixer'))
.pipe($.sourcemaps.write())
.pipe(gulp.dest(path.join(conf.paths.tmp, '/serve/app/')))
.pipe(browserSync.reload({ stream: true }));
});
I also had the same problem using the gulp generator but only with bootstrap-sass. I added the following to get bootstrap to work:
conf.js
exports.wiredep = {
exclude: [/\/bootstrap\.js$/, /\/bootstrap-sass\/.*\.js/, /\/bootstrap\.css/],
directory: 'bower_components'
};
bower.json
"overrides": {
"bootstrap-sass": {
"main": [
"assets/stylesheets/_bootstrap.scss",
"assets/fonts/bootstrap/glyphicons-halflings-regular.eot",
"assets/fonts/bootstrap/glyphicons-halflings-regular.svg",
"assets/fonts/bootstrap/glyphicons-halflings-regular.ttf",
"assets/fonts/bootstrap/glyphicons-halflings-regular.woff",
"assets/fonts/bootstrap/glyphicons-halflings-regular.woff2"
]
}
},

gulp browserify reactify task is quite slow

I am using Gulp as my task runner and browserify to bundle my CommonJs modules.
I have noticed that running my browserify task is quite slow, it takes around 2 - 3 seconds, and all I have is React and a few very small components I have built for development.
Is there a way to speed up the task, or do I have any noticeable problems in my task?
gulp.task('browserify', function() {
var bundler = browserify({
entries: ['./main.js'], // Only need initial file
transform: [reactify], // Convert JSX to javascript
debug: true, cache: {}, packageCache: {}, fullPaths: true
});
var watcher = watchify(bundler);
return watcher
.on('update', function () { // On update When any files updates
var updateStart = Date.now();
watcher.bundle()
.pipe(source('bundle.js'))
.pipe(gulp.dest('./'));
console.log('Updated ', (Date.now() - updateStart) + 'ms');
})
.bundle() // Create initial bundle when starting the task
.pipe(source('bundle.js'))
.pipe(gulp.dest('./'));
});
I am using Browserify, Watchify, Reactify and Vinyl Source Stream as well as a few other unrelated modules.
var browserify = require('browserify'),
watchify = require('watchify'),
reactify = require('reactify'),
source = require('vinyl-source-stream');
Thanks
See fast browserify builds with watchify. Note that the only thing passed to browserify is the main entry point, and watchify's config.
The transforms are added to the watchify wrapper.
code from article pasted verbatim
var gulp = require('gulp');
var gutil = require('gulp-util');
var sourcemaps = require('gulp-sourcemaps');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var watchify = require('watchify');
var browserify = require('browserify');
var bundler = watchify(browserify('./src/index.js', watchify.args));
// add any other browserify options or transforms here
bundler.transform('brfs');
gulp.task('js', bundle); // so you can run `gulp js` to build the file
bundler.on('update', bundle); // on any dep update, runs the bundler
function bundle() {
return bundler.bundle()
// log errors if they happen
.on('error', gutil.log.bind(gutil, 'Browserify Error'))
.pipe(source('bundle.js'))
// optional, remove if you dont want sourcemaps
.pipe(buffer())
.pipe(sourcemaps.init({loadMaps: true})) // loads map from browserify file
.pipe(sourcemaps.write('./')) // writes .map file
//
.pipe(gulp.dest('./dist'));
}
You have to use watchify and enable its cache. Take a look at :
https://www.codementor.io/reactjs/tutorial/react-js-browserify-workflow-part-2
and for more optimisation when building source-map you could do that :
cd node_modules/browserify && npm i substack/browser-pack#sm-fast
this would safe you half of time
part of my gulpfile.js
var gulp = require('gulp');
var uglify = require('gulp-uglify');
var htmlreplace = require('gulp-html-replace');
var source = require('vinyl-source-stream');
var browserify = require('browserify');
var watchify = require('watchify');
var reactify = require('reactify');
var streamify = require('gulp-streamify');
var path = {
OUT : 'build.js',
DEST2 : '/home/apache/www-modules/admimail/se/se',
DEST_BUILD : 'build',
DEST_DEV : 'dev',
ENTRY_POINT : './src/js/main.jsx'
};
gulp.task('watch', [], function() {
var bundler = browserify({
entries : [ path.ENTRY_POINT ],
extensions : [ ".js", ".jsx" ],
transform : [ 'reactify' ],
debug : true,
fullPaths : true,
cache : {}, // <---- here is important things for optimization
packageCache : {} // <---- and here
});
bundler.plugin(watchify, {
// delay: 100,
// ignoreWatch: ['**/node_modules/**'],
// poll: false
});
var rebundle = function() {
var startDate = new Date();
console.log('Update start at ' + startDate.toLocaleString());
return bundler.bundle(function(err, buf){
if (err){
console.log(err.toString());
} else {
console.log(' updated in '+(new Date().getTime() - startDate.getTime())+' ms');
}
})
.pipe(source(path.OUT))
.pipe(gulp.dest(path.DEST2 + '/' + path.DEST_DEV))
;
};
bundler.on('update', rebundle);
return rebundle();
});
gulp.task('default', [ 'watch' ]);
Many thanks to #PHaroZ for that answer. I had to modify a little bit that code for my needs though. I am working with ReactJS on Symfony2 framework and all my builds were taking 7s-21s!!! Crazy.. So that's what I have now:
var path = {
OUT : 'app.js',
DEST_BUILD : './src/MyBundle/Resources/js/dist',
ENTRY_POINT : './src/MyBundle/Resources/js/src/app.js'
};
gulp.task('watch', [], function() {
var bundler = browserify({
entries : [ path.ENTRY_POINT ],
extensions : [ ".js", ".jsx" ],
// transform : [ 'reactify' ],
debug : true,
fullPaths : true,
cache : {}, // <---- here is important things for optimization
packageCache : {} // <---- and here
}).transform("babelify", {presets: ["es2015", "react"]});
bundler.plugin(watchify, {
// delay: 100,
// ignoreWatch: ['**/node_modules/**'],
// poll: false
});
var rebundle = function() {
var startDate = new Date();
console.log('Update start at ' + startDate.toLocaleString());
return bundler.bundle(function(err, buf){
if (err){
console.log(err.toString());
} else {
console.log(' updated in '+(new Date().getTime() - startDate.getTime())+' ms');
}
})
.pipe(source(path.OUT))
.pipe(gulp.dest(path.DEST_BUILD))
;
};
bundler.on('update', rebundle);
return rebundle();
});
Now first compile takes around 20s and each time I update my file it takes around 800ms. It's just enough time to switch from IDE to my browser.

Categories

Resources