I don't know if I missed something or made a mistake. But requiring a module only returns an empty object.
This is just a sample of my project.
Tools I'm using:
gulp - 3.9.1
browserify - 13.0.0
vinyl-source-stream - 1.1.0
Here is my working directory:
root/
dist/
src/
external.js
main.js
gulpfile.js
main.js
var External = require('./external.js');
console.log(External);
external.js
function Hello() {
return 'Hello from the otherside!';
}
module.exports = {
testFunc: Hello
};
gulpfile.js
var browserify = require('browserify');
var vinyl_source_stream = require('vinyl-source-stream');
gulp.task('concat', function() {
return browserify('./src/main.js')
.bundle()
.pipe(vinyl_source_stream('bundle.js'))
.pipe(gulp.dest('./dist/'))
});
First:
module.exports = function() {
testFunc: Hello
};
so that you can export an object prototype.
Second
var External = require('./external.js')(); // Notice the ()
so that you can execute that prototype and get an instance of the object.
I am working on a project where I am using gulp. However, gulp keeps throwing an error saying it cannot find the AppAPI.js file in my work environment. I am building with Reactjs and Flux. I believe the problem may be in my gulpfile, but after trying various versions of the code, I have not been able to get anywhere. Could someone take a look and see if indeed my code is wrong or if there could be something else going wrong? Here is my gulpfile:
var gulp = require('gulp');
var browserify = require('browserify');
var reactify = require('reactify'); // Converts jsx to js
var source = require('vinyl-source-stream'); // Converts string to a stream
gulp.task('browserify', function(){
browserify('./src/js/main.js')
.transform('reactify')
.bundle()
.pipe(source('main.js'))
.pipe(gulp.dest('dist/js'));
});
gulp.task('copy', function(){
gulp.src('src/index.html')
.pipe(gulp.dest('dist'));
gulp.src('src/css/*.*')
.pipe(gulp.dest('dist/css'));
gulp.src('src/js/vendors/*.*')
.pipe(gulp.dest('dist/js'));
});
gulp.task('default', ['browserify', 'copy'], function(){
return gulp.watch('src/**/*.*', ['browserify', 'copy']);
});
I am requiring appAPI.js in my main.js file:
var App = require('./components/App');
var React = require('react');
var ReactDOM = require('react-dom');
var AppAPI = require('./utils/appAPI.js');
ReactDOM.render(
<App />,
document.getElementById('app')
);
Here is the appAPI.js code:
var AppActions = require('../actions/AppActions');
module.exports = {
}
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.
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/'));
});
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.