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.
Related
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, ));
I hate javascript tooling.
I have this config file:
var source = require('vinyl-source-stream');
var gulp = require('gulp');
var tap = require('gulp-tap');
var gutil = require('gulp-util');
var concat = require('gulp-concat');
var csso = require('gulp-csso');
var jshint = require('gulp-jshint');
var watchify = require('watchify');
var browserify = require('browserify');
var uglify = require('gulp-uglify');
var streamify = require('gulp-streamify');
gulp.task('prod', ['assets', 'prod-css'], function() {
return browserify('./src/main.js', {
standalone: standalone
}).transform('babelify',
{ presets: ["#babel/preset-env"],
plugins: [] })
.bundle()
.on('error', onError)
.pipe(source('okeyground.min.js'))
.pipe(streamify(uglify()))
.pipe(gulp.dest(destination));
});
when I add a debugger; command it doesn't get produced in the minified js. Does it get removed, or how can I put it in.
In your code set the drop_debugger property to false in the compress options:
.pipe(
uglify({
compress: {
drop_debugger: false,
},
})
)
I have a task gulp dev that should merge a array of JS files into one in dist/js however I cant seem to get the gulp command to create the file dist/js, Can anyone see where I have gone wrong been at this 9 hrs now.
Thanks
Gulp file
gulp.task("dev", function () {
// set the dev config (cache in utils.js)
utils.setConfig({
env: "dev",
watch: true,
notify: true,
tasks: ["js", "css", "copy", "bower", "svg-sprite"]
});
// build with this config
utils.build();
});
then ...
task/js
var gulp = require("gulp"),
utils = require("./utils"),
config = utils.loadConfig(),
gulpif = require("gulp-if"),
fs = require("fs"),
uglify = require("gulp-uglify"),
sourcemaps = require("gulp-sourcemaps"),
browserify = require("browserify"),
shim = require("browserify-shim"),
through2 = require("through2"),
babelify = require("babelify"),
minify = require('gulp-minify'),
replaceName = require('gulp-replace-name');
// dev/default settings
utils.setTaskConfig("js", {
default: {
// Pass array instead of single file!
src: [
config.root + "/js/index.js",
config.root + "/js/owlCarousel.js",
config.root + "/js/search/search.js",
// Angular 1.x doesn't play well with CommonJS modules :(
config.root + "/js/search/angular-1.5.1.min.js",
config.root + "/js/search/angular-animate-1.5.1.min.js",
config.root + "/js/search/angular-sanitize-1.5.1.min.js"
],
dest: config.dest + "/js",
// js uglify options, to skip, set value to false or omit entirely
// otherwise, pass options object (can be empty {})
uglify: false,
// browserify options
browserify: {
debug: true // enable sourcemaps
}
},
prod: {
browserify: {},
// uglify javascript for production
uglify: {}
}
});
// register the watch
utils.registerWatcher("js", [
config.root + "/js/**/*.js",
config.root + "/js/**/*.jsx"
]);
/* compile application javascript */
gulp.task("js", function(){
var js = utils.loadTaskConfig("js");
// for browserify usage, see https://medium.com/#sogko/gulp-browserify-the-gulp-y-way-bb359b3f9623
// ^^ we can't use vinyl-transform anymore because it breaks when trying to use b.transform()
// https://github.com/sogko/gulp-recipes/tree/master/browserify-vanilla
var browserifyIt = through2.obj(function (file, enc, callback){
// https://github.com/substack/node-browserify/issues/1044#issuecomment-72384131
var b = browserify(js.browserify || {}) // pass options
.add(file.path) // this file
.transform(babelify)
.transform(shim);
b.bundle(function(err, res){
if (err){
callback(err, null); // emit error so drano can do it's thang
}
else {
file.contents = res; // assumes file.contents is a Buffer
callback(null, file); // pass file along
}
});
});
return gulp.src(js.src)
.pipe(utils.drano())
.pipe(browserifyIt)
.pipe(sourcemaps.init({ loadMaps: true })) // loads map from browserify file
.pipe(gulpif((js.uglify), uglify(js.uglify)))
.pipe(minify(({
ignoreFiles: ['*.min.js', 'search.js']
})))
.pipe(sourcemaps.write("./"))
.pipe(gulp.dest(js.dest));
});
gulp.src([
'./dist/js/*.min.js',
'./dist/js/*-min.js',
'./dist/js/amcharts.js',
'./dist/js/amstock.js',
'./dist/js/table-childssorter.js',
'./dist/js/serial.js',
'./dist/js/vendor.js',
'./dist/js/jquery-3.1.1.js',
'./dist/js/jquery.tablesorter.js',
'./dist/js/search.js'
])
.pipe(replaceName(/\-min.js/g, '.js'))
.pipe(gulp.dest('./dist/minified/js'));
I try to use transform-es2015-classes plugin with gulp, browserify, reactify.
var gulp = require('gulp');
var browserify = require('browserify');
var babelify = require('babelify');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var uglify = require('gulp-uglify');
var sourcemaps = require('gulp-sourcemaps');
var livereload = require('gulp-livereload');
var reactify = require('reactify');
var util = require('gulp-util');
gulp.task("reactcompile", function () {
// app.js is your main JS file with all your module inclusions
return browserify({entries: './src/main/app/reactjs/react-app.js', debug: true})
.transform("babelify",
{
plugins: [
'transform-es2015-classes', { loose: true }
],
presets: ["es2015", "react", "stage-0"]
})
.bundle()
.on('error', util.log.bind(util, 'Browserify Error'))
.pipe(source('react-app.js'))
.pipe(buffer())
.pipe(gulp.dest('./build'))
.pipe(livereload());
});
As I run gulp, I get the error:
[12:06:45] Browserify Error { Error: Plugin 1 specified in "base"
provided an invalid property of "loose" while parsing file: mypath\react-app.js
Is my syntax wrong or what is the problem?
You're missing a set of []s.
plugins: [
'transform-es2015-classes', { loose: true }
]
should be
plugins: [
['transform-es2015-classes', { loose: true }]
]
so the plugin and its arguments are a single item in the plugins array.
I'm trying to create a gulp task with browserify and babelify. Here is the task:
var gulp = require('gulp');
var browserify = require('gulp-browserify');
var source = require('vinyl-source-stream');
var babelify = require('babelify');
gulp.task('js', function () {
browserify('./resources/js/*.js')
.transform(babelify)
.bundle()
.pipe(source('*.js'))
.pipe(gulp.dest('./public/js'));
});
I found a few sample code, tried to use them, but the result was always the same.
When i run the task, and save my example.js file, the following error occurs:
TypeError: browserify(...).transform is not a function
What am I doing wrong?
You're mixing up the API for browserify and gulp-browserify.
From the gulp-browserify docs, you'll want to do something like this:
var gulp = require('gulp')
var browserify = require('gulp-browserify')
gulp.task('js', function () {
gulp.src('./resources/js/*.js')
.pipe(browserify({
transform: ['babelify'],
}))
.pipe(gulp.dest('./public/js'))
});
EDIT: Since this question was first answered, gulp-browserify has been abandoned and gulp has evolved a great deal. If you'd like to achieve the same thing with a newer version of gulp, you can follow the guides provided by the gulp team.
You'll end up with something like the following:
var browserify = require('browserify');
var babelify = require('babelify');
var gulp = require('gulp');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var sourcemaps = require('gulp-sourcemaps');
var util = require('gulp-util');
gulp.task('default', function () {
var b = browserify({
entries: './resources/test.js',
debug: true,
transform: [babelify.configure({
presets: ['es2015']
})]
});
return b.bundle()
.pipe(source('./resources/test.js'))
.pipe(buffer())
.pipe(sourcemaps.init({ loadMaps: true }))
// Add other gulp transformations (eg. uglify) to the pipeline here.
.on('error', util.log)
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest('./public/js/'));
});