how to use the exclude in browserify? - browserify

in browserify-handbook, exclude part,it gives an example of using the exclude:
$ npm install jquery
$ browserify -r jquery --standalone jquery > jquery-bundle.js
then we want to just require('jquery') in a main.js:
var $ = require('jquery');
$(window).click(function () { document.body.bgColor = 'red' });
defering to the jquery dist bundle so that we can write:
<script src="jquery-bundle.js"></script>
<script src="bundle.js"></script>
and not have the jquery definition show up in bundle.js, then while compiling the main.js, you can --exclude jquery:
browserify main.js --exclude jquery > bundle.js
but when i try to run this sample,i got an error of "Uncaught Error: Cannot find module 'jquery'"
i know if i use standalone,i can just use 'jquery' as a global variable, but it's not modular, so i still want to do as the sample using "require('jquery')", so,what shall i do to achieve it?

I finally got this functionality working using information found here:
https://truongtx.me/2014/03/20/browserify-bring-nodejs-modules-to-browser/
I wonder if the docs you found are out of date now...
The working solution in the above link uses the '-x' option ('external') rather than the '-u' option ('exclude')
The linked article also demonstrates how to set this up using gulp.
I'm pasting the relevant content from the above-linked web site:
$ browserify -r foo.js > foo-out.js
$ browserify -r d3-browserify > d3-browserify-out.js
For main.js
$ browserify -x ./foo.js -x d3-browserify main.js > main-bundle.js
In the browser, you need to include all those 3 files
<script src="foo-out.js"></script>
<script src="d3-browserify-out.js"></script>
<script src="main-bundle.js"></script>
Update: The link I posted does not seem to be working so I'm including my current gulpfile.js. I'm new to gulp and javascript, so there may be a better way to do this stuff. But this current setup does basically work:
var browserify = require('browserify');
var gulp = require('gulp');
var watchify = require('watchify');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var jshint = require('gulp-jshint');
var uglify = require('gulp-uglify');
var sourcemaps = require('gulp-sourcemaps');
var gutil = require('gulp-util');
var del = require('del');
const PATH_OPTS = {
src_dir: './client/js/src/',
main_file_path: './client/js/src/main.js',
output_file_name: 'disco.js',
output_dir: './public/js/',
common_lib_file_name: 'common.js'
};
const LIBS = ['paper', 'jquery', 'tocktimer'];
gulp.task("clientlib", function() {
var bundler = browserify({
debug: false
});
LIBS.forEach(function(lib) {
bundler.require(lib);
});
bundler.bundle()
.pipe(source(PATH_OPTS.common_lib_file_name))
// uglify seems to need a buffered stream...
.pipe(buffer())
.pipe(uglify())
.on('error', gutil.log)
.pipe(gulp.dest(PATH_OPTS.output_dir));
});
gulp.task('client', function () {
var bundler = browserify({
debug: true,
cache: {},
packageCache: {},
fullPaths: true
});
bundler = watchify(bundler);
bundler.on('update', function(){
bundle(bundler);
});
bundler.on('log', function(msg) {
gutil.log(msg);
});
bundler.add(PATH_OPTS.main_file_path);
LIBS.forEach(function(lib) {
bundler.external(require.resolve(lib, { expose: lib }));
});
return bundle(bundler);
});
function bundle(bundler) {
return bundler.bundle()
.pipe(source(PATH_OPTS.output_file_name))
.pipe(buffer())
.pipe(sourcemaps.init({loadMaps: true}))
// Add transformation tasks to the pipeline here.
.pipe(uglify())
.on('error', gutil.log)
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest(PATH_OPTS.output_dir));
}
gulp.task('lint', function() {
return gulp.src(PATH_OPTS.src_dir + '*.js')
.pipe(jshint())
.pipe(jshint.reporter('default'));
});
gulp.task('clean', function () {
return del([
PATH_OPTS.output_dir + '/*.*'
]);
});
gulp.task('full', ['lint', 'clean', 'clientlib', 'client']);
gulp.task('default', ['lint', 'client']);

Related

Object not defined in gulp

var gulp = require('gulp');
var browserSync = require('browser-sync');
var sass = require('gulp-sass');
var prefix = require('gulp-autoprefixer');
var cp = require('child_process');
var pug = require('gulp-pug');
var jekyll = process.platform === 'win32' ? 'jekyll.bat' : 'jekyll';
var messages = {
jekyllBuild: '<span style="color: grey">Running:</span> $ jekyll build'
};
/**
* Build the Jekyll Site
*/
gulp.task('jekyll-build', function (done) {
browserSync.notify(messages.jekyllBuild);
return cp.spawn( jekyll , gulp.task('build'), {stdio: 'inherit'})
.on('close', done);
});
/**
* Rebuild Jekyll & do page reload
*/
gulp.task('jekyll-rebuild', gulp.task('jekyll-build'), function () {
browserSync.reload();
});
/**
* Wait for jekyll-build, then launch the Server
*/
gulp.task('browser-sync', gulp.series('sass', 'jekyll-build'), function() {
browserSync({
server: {
baseDir: '_site'
},
notify: false
});
});
/**
* Compile files from _scss into both _site/css (for live injecting) and site (for future jekyll builds)
*/
gulp.task('sass', function () {
return gulp.src('raw-assets/sass/**/*.scss')
.pipe(sass().on('error', sass.logError))
.pipe(autoprefixer(['last 15 versions', '> 1%', 'ie 8', 'ie 7'], { cascade: true }))
. pipe(gulp.dest('assets/css'))
});
/**
* Compile files from _pugfiles into _includes (for live injecting) and site
(for future jekyll builds)
*/
gulp.task('pug', function buildHTML() {
return gulp.src('_pugfiles/*.pug')
.pipe(pug({
// Your options in here.
pretty: true
}))
.pipe(gulp.dest('_includes'));
});
/**
* Watch scss files for changes & recompile
* Watch html/md files/pug files, run jekyll & reload BrowserSync
*/
gulp.task('watch', function () {
gulp.watch('assets/css/**', gulp.task('sass'));
gulp.watch(['*.html', '_layouts/*.html', '_includes/*'], gulp.task('jekyll-rebuild'));
gulp.watch(['_pugfiles/*.pug'], gulp.task('pug'));
});
/**
* Default task, running just `gulp` will compile the sass,
* compile the jekyll site, launch BrowserSync & watch files.
*/
gulp.task('default', gulp.series('browser-sync', 'watch'));
I changed the
gulp.task('', [])
to
gulp.task('', gulp.series())
But it still gives an error of sass undefined.
I upgraded my gulp to the latest gulp and the gulpfile is not working anymore. I want to be able to run the gulp command and run everything the way it was before gulp 4. Any ways to fix this aside from reverting to the old version of gulp.
Move your 'sass' task before the 'browser-sync' task where it is first called.
I can't find the reference right now but I think when you use the gulp.task registration syntax (instead of functions as is actually recommended in gulp4 now) that you cannot refer to a task that is registered later in the file.
Also you have some other errors in your code. This line (and others like it):
gulp.task('browser-sync', gulp.series('sass', 'jekyll-build'), function() {
should be:
gulp.task('browser-sync', gulp.series('sass', 'jekyll-build', function() {
And:
gulp.task('jekyll-rebuild', gulp.task('jekyll-build'), function () {
browserSync.reload();
});
should be:
gulp.task('jekyll-rebuild', gulp.series('jekyll-build', function () {
browserSync.reload();
}));
Here is a very good migrating to gulp4 article.

why my less source maps don't work?

I use the gulp-less compiler with gulp-sourcemaps write the source maps file.
but it don't work in my chrome dev tool, I can't see the content of less. only css file.
it's my gulp file:
var gulp = require('gulp');
var less = require('gulp-less');
var path = require('path');
var sourcemaps = require('gulp-sourcemaps');
gulp.task('less', function () {
return gulp.src('src/less/*.less')
.pipe(less())
.pipe(sourcemaps.init())
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('src/css'));
});
gulp.task('watch', function() {
gulp.watch('src/less/*.less', ['less']);
});

Browser-sync TypeError args.cb is not a function

I'm using browser-sync in gulp task for example :
gulp.task('gulp-task',function(){
browserSync.init({
server:{
baseDir: 'app'
}
})
//rest of task
});
I use this gulp task in gulp watch for( for example ) app/**/*.html like :
gulp.task('watch',function(){
gulp.watch('app/**/*.html', ['gulp-task']);
});
for first time change in html files everything is ok but for next changes i get error:
TypeError: args.cbn is not a function ...
guys said to install latest version for browser-sync with command below :
npm install browser-sync#latest --save-dev
and it doesn't helped.
I'm getting the same error. what's wrong?
I also ran into this issue and solved it by removing the brackets from the callback in the watch task.
Try changing your watch task to:
gulp.task('watch',function(){
gulp.watch(['app/**/*.html'], 'gulp-task');
});
Or better yet, try using the reload method with something like this:
var gulp = require('gulp');
var browserSync = require('browser-sync').create();
var jshint = require('gulp-jshint');
var watch = require('gulp-watch');
var reload = browserSync.reload;
gulp.task('default', ['jshint', 'serve', 'watch']);
gulp.task('jshint', function() {
return gulp.src('src/app/**/*.js')
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish'));
});
// Static server
gulp.task('serve', function() {
browserSync.init({
server: {
baseDir: "./src"
}
});
});
gulp.task('watch', function() {
gulp.watch(['src/**/*.html', 'src/app/**/*.js'], reload);
});
After reading the document of browser-sync,I noticed that the method .init( config, cb ) has two parameters.So,change your code to this:
gulp.task('gulp-task',function(){
browserSync.init({
server:{
baseDir: 'app'
}
})
//rest of task
},function(){
// something you want to do
});
While defining the 'watch' we need to declare what all tasks need to be run before watch, this will sort the problem out.
Extra parameter with pre-planned tasks needs to be added in the watch task list of parameters.
gulp.task('watch', ['browserSync', 'sass'], function(){...})
var gulp = require('gulp');
var sass = require('gulp-sass');
var browserSync = require('browser-sync').create();
gulp.task('hello', function() {
console.log('Hello Gulp-Shash');
});
gulp.task('sass', function(){
return gulp.src('app/scss/**/*.scss')
.pipe(sass())
.pipe(gulp.dest('app/css'))
.pipe(browserSync.reload({
stream: true
}))
});
gulp.task('browserSync', function() {
browserSync.init({
server: {
baseDir: 'app'
},
})
})
gulp.task('watch', ['browserSync', 'sass'], function(){
gulp.watch('app/scss/**/*.scss', ['sass']);
})

Using Babelify to compile React results in React Router being undefined

I'm using Gulp for my build system, with Browserify for compiling my JS. I had been using Reactify for JSX compilation, but thought I'd switch to Babelify to get some additional ES2015 features. No errors are thrown when compiling, but when I load my site in the browser I get the following error in my JS console:
Uncaught ReferenceError: Router is not defined
The line the error is referring to is:
var React = require('react');
in the main component file that is being loaded on the page.
The places where I am importing React Router are in my App.jsx file (which is the entrypoint for the application) and my routes.jsx file, where I define the routes:
App.jsx
var React = require('react'),
Router = require('react-router'),
routes = require('./routes.jsx');
Router.run(routes, function(Handler, state) {
var routeClasses = '';
for (var i = 1; i < state.routes.length; i++) {
routeClasses += state.routes[i].name + ' ';
}
React.render(<Handler classes={routeClasses.trim()} />, document.getElementById('root'));
});
routes.jsx
var React = require('react');
Router = require('react-router'),
Route = Router.Route,
DefaultRoute = Router.DefaultRoute,
App = require('./_layout/App.jsx'),
Editor = require('./editor/Editor.jsx');
module.exports = (
<Route name="app" path="/" handler={App}>
<DefaultRoute name="editor" handler={Editor} />
</Route>
);
Everything was working fine when using Reactify rather than Babelify. I'm using Gulp for my build process:
gulp.task('js', function() {
var browserify = require('browserify'),
watchify = require('watchify'),
minifyify = require('minifyify'),
babelify = require('babelify');
function bundle() {
b.bundle()
.on('error', function(error){
gutil.log(error);
})
.pipe(source('app.js'))
.pipe(gulp.dest(paths.client.js.build))
.pipe(gulpif(!isStartup, browserSync.stream()));
isStartup = false;
}
var map = isProd ? false : 'app.map.json';
var b = browserify({
cache: {},
packageCache: {},
entries: paths.client.js.dev,
debug: true,
plugin: [watchify]
})
.transform(babelify, {presets: ['es2015', 'react']})
.plugin('minifyify', {
map: map,
output: paths.client.js.build + 'app.map.json',
});
b.on('update', function(){
bundle();
});
b.on('log', gutil.log); // output build logs to terminal
bundle();
});
The working version, using Reactify, simply omits the .transform(babelify...) line and adds transform: reactify to the browserify() initialization code, i.e.
var b = browserify({
cache: {},
packageCache: {},
entries: paths.client.js.dev,
debug: true,
transform: reactify,
plugin: [watchify]
});
It's working with es2015 import X from Y syntax, e.g.
import React from 'react'

Gulp error: events.js:72

I've been trying out (or trying to get working) a jekyll style guide from: https://github.com/davidhund/jekyll-styleguide#user-content-requirements
My gulpfile is:
var gulp = require('gulp');
var sass = require('gulp-ruby-sass');
var autoprefixer = require('gulp-autoprefixer');
var browserSync = require('browser-sync');
var rename = require('gulp-rename');
var concat = require('gulp-concat');
var minifycss = require('gulp-minify-css');
var uglify = require('gulp-uglify');
var clean = require('gulp-clean');
var notify = require('gulp-notify');
var plumber = require('gulp-plumber');
// Handy file paths
paths = {
scss: "./static/scss/",
css: "./static/css/",
img: "./static/img/",
js: "./static/js/"
}
// SASS
gulp.task('sass', function() {
// Be specific in what file to process
return gulp.src(paths.scss+'app.scss')
.pipe(sass({ style: 'expanded' }))
.pipe(autoprefixer('> 5%', 'last 2 version', 'ie 9'))
.pipe(minifycss())
.pipe(rename({suffix: '.min'}))
.pipe(gulp.dest(paths.css))
// .pipe(gulp.dest('./_site/static/css/'))
// .pipe(notify({ message: 'Styles task complete' }));
});
// COPY CSS
gulp.task('copycss', function() {
return gulp.src(paths.css+'app.min.css')
.pipe(gulp.dest('./_site/static/css/'))
// .pipe(notify({ message: 'Copied Minified CSS to _site/static/css' }));
});
// JEKYLL
// Start a `jekyll build` task
// From: http://stackoverflow.com/questions/21293999/use-jekyll-with-gulp
gulp.task('jekyll-build', function() {
require('child_process').spawn('jekyll', ['build', '--config=_config.dev.yml'], {stdio: 'inherit'});
});
// Start a `jekyll build --watch` task
gulp.task('jekyll-watch', function() {
require('child_process').spawn('jekyll', ['build', '--watch', '--config=_config.dev.yml'], {stdio: 'inherit'});
});
// BROWSER-SYNC
gulp.task('browser-sync', function() {
// reload when Jekyll-generated files change
browserSync.init(['./_site/static/**/*.css', './_site/**/*.html'], {
server: {
baseDir: './_site/'
}
});
});
// WATCH
gulp.task('watch', function() {
// TEST: [Only] Run `jekyll build` when I update (the version in) settings.yml
// gulp.watch('./_config.yml', ['jekyll']);
// Run Sass when I update SCSS files
gulp.watch(paths.scss+'**/*.scss', ['sass', 'copycss']);
// gulp.watch(paths.js+'**/*.js', ['scripts']);
// gulp.watch(paths.img+'**/*', ['images']);
});
// DEFAULT task
gulp.task('default', ['jekyll-watch', 'watch','browser-sync']);
Whenever I run gulp I just get:
events.js:72
throw er; // Unhandled 'error' event
^
Error: spawn ENOENT
at errnoException (child_process.js:998:11)
at Process.ChildProcess._handle.onexit (child_process.js:789:34)
The problem you are facing is that you are not handling error, so, when gulp finds an error, it throw it, but "nobody" is taking care of it, which causes gulp to break.
In order to keep executing gulp, you have to define your error handlers and do whatever you want to do with error, typically, print on the cli what is going on.
You also need to identify which part of your code is "throwing" the error, in your case, its caused by the "watchers": a watcher listen for additional events or to add files to the watch. So, a watcher is throwing the error.
You have to catch it !
Add an on handler event after the execution of plugins, and pass this error to a function that will pint it (or something else), but will not break "the watch" (John Snow will be proud) and allows you to identify the error, fix it, at keep watching without restarting gulp manually.
PS: Don't forgot to define "the catcher function" !
Your code could be something like this:
var gulp = require('gulp');
var sass = require('gulp-ruby-sass');
var autoprefixer = require('gulp-autoprefixer');
var browserSync = require('browser-sync');
var rename = require('gulp-rename');
var concat = require('gulp-concat');
var minifycss = require('gulp-minify-css');
var uglify = require('gulp-uglify');
var clean = require('gulp-clean');
var notify = require('gulp-notify');
var plumber = require('gulp-plumber');
// Handy file paths
paths = {
scss: "./static/scss/",
css: "./static/css/",
img: "./static/img/",
js: "./static/js/"
}
// SASS
gulp.task('sass', function() {
// Be specific in what file to process
return gulp.src(paths.scss+'app.scss')
.pipe(sass({ style: 'expanded' })).on('error', errorHandler)
.pipe(autoprefixer('> 5%', 'last 2 version', 'ie 9'))
.pipe(minifycss())
.pipe(rename({suffix: '.min'}))
.pipe(gulp.dest(paths.css))
// .pipe(gulp.dest('./_site/static/css/'))
// .pipe(notify({ message: 'Styles task complete' }));
});
// COPY CSS
gulp.task('copycss', function() {
return gulp.src(paths.css+'app.min.css')
.pipe(gulp.dest('./_site/static/css/'))
// .pipe(notify({ message: 'Copied Minified CSS to _site/static/css' }));
});
// JEKYLL
// Start a `jekyll build` task
// From: http://stackoverflow.com/questions/21293999/use-jekyll-with-gulp
gulp.task('jekyll-build', function() {
require('child_process').spawn('jekyll', ['build', '--config=_config.dev.yml'], {stdio: 'inherit'});
});
// Start a `jekyll build --watch` task
gulp.task('jekyll-watch', function() {
require('child_process').spawn('jekyll', ['build', '--watch', '--config=_config.dev.yml'], {stdio: 'inherit'});
});
// BROWSER-SYNC
gulp.task('browser-sync', function() {
// reload when Jekyll-generated files change
browserSync.init(['./_site/static/**/*.css', './_site/**/*.html'], {
server: {
baseDir: './_site/'
}
});
});
// WATCH
gulp.task('watch', function() {
// TEST: [Only] Run `jekyll build` when I update (the version in) settings.yml
// gulp.watch('./_config.yml', ['jekyll']);
// Run Sass when I update SCSS files
gulp.watch(paths.scss+'**/*.scss', ['sass', 'copycss']);
// gulp.watch(paths.js+'**/*.js', ['scripts']);
// gulp.watch(paths.img+'**/*', ['images']);
});
// DEFAULT task
gulp.task('default', ['jekyll-watch', 'watch','browser-sync']);
// Handle the error
function errorHandler (error) {
console.log(error.toString());
this.emit('end');
}
Note the error handler definition at the end and the addition of .on('error', errorHandler) on your sass task.