Code Monkey home page Code Monkey logo

gulp-browserify's Introduction

NOTE: THIS PLUGIN IS NO LONGER MAINTAINED , checkout gulp-bro for a similar plugin, or the recipes by gulp team for reference on using browserify with gulp.

Build Status NPM version

gulp-browserify

Packagegulp-browserify
Description Bundle modules with BrowserifyJS
Node Version >= 0.9
Gulp Version 3.x

Usage

Install

npm install --save-dev gulp-browserify

Example

var gulp = require('gulp');
var browserify = require('gulp-browserify');

// Basic usage
gulp.task('scripts', function() {
	// Single entry point to browserify
	gulp.src('src/js/app.js')
		.pipe(browserify({
		  insertGlobals : true,
		  debug : !gulp.env.production
		}))
		.pipe(gulp.dest('./build/js'))
});

Make sure to pipe only entry points. Browserify will take care of other dependencies for you.

Options

transform

Type : [String || function]

Specifies a pipeline of functions (or module names) through which the browserified bundle will be run. Check out the list of transforms on node-browserify.

Languages that compile to JavaScript

If you want to bundle files with extensions other than .js or .json, omit contents from streamed files and set extensions option.

Let's say you want to browserify CoffeeScript, install coffeeify and:

var gulp = require('gulp');
var browserify = require('gulp-browserify');
var rename = require('gulp-rename');

gulp.task('coffee', function() {
  gulp.src('src/coffee/app.coffee', { read: false })
    .pipe(browserify({
      transform: ['coffeeify'],
      extensions: ['.coffee']
    }))
    .pipe(rename('app.js'))
    .pipe(gulp.dest('./build/js'))
});

If you forget { read: false }, gulp-browserify will passes the contents stream of a incoming file to node-browserify. Then node-browserify names the stream as fake_xxx.js and process it. Some transforms such as coffeeify determines whether to transform files with extensions. That is why you need { read: false } for AltJS.

debug

Type : Boolean

Enable source map support. !gulp.env.production would work well.

extensions

Type: [String]

Array of extensions that you want to skip in require() calls in addition to .js and .json. Don't forget ..

With { extensions: ['.coffee'] }, you can't do require('app'). Instead, you have to do require('app.coffee').

ignore

Type: [String]

Array of paths which should be passed to the ignore function of browserify.

resolve

Type: Function

Custom module name resolution function. From node-browserify documentation:

You can give browserify a custom opts.resolve() function or by default it uses browser-resolve.

Obviously, this function must implement the same API as browser-resolve.

Other Options

Any other options you provide will be passed through to browserify. This is useful for setting things like standalone or ignoreGlobals.

Custom options

nobuiltins

Remove builtins modules defined in lib/builtins.js (browserify module). opts.builtins must be not defined and opts.nobuiltins can be an Array of Strings or simply a String.

gulp.task('scripts', function() {
  gulp.src(['src/index.js'])
    .pipe(browserify({
      nobuiltins: 'events querystring'
    }))
    .pipe(gulp.dest('./build/js'))
});

Browserify-Shim

Example configuration

gulp.task('scripts', function() {
	//single entry point to browserify
	gulp.src(['src/index.js'])
		.pipe(browserify({
		  shim: {
		    angular: {
                path: '/vendor/angular/angular.js',
                exports: 'angular'
		    },
            'angular-route': {
                path: '/vendor/angular-route/angular-route.js',
                exports: 'ngRoute',
                depends: {
                    angular: 'angular'
                }
            }
		  }
		}))
		.pipe(concat('dest.js'))
		.pipe(gulp.dest('./build'))
});

More information about configuring browserify-shim can be found here.

Events

Other than standard Node.js stream events, gulp-browserify emits its own events.

prebundle

.on('prebundle', function(bundler){})

Event triggered just before invoking bundler.bundle() and provides the bundler object to work with in the callback.

This is especially useful if you want to require(), external() or other methods of node-browserify.

gulp.task('scripts', function() {
  gulp.src('src/js/app.js')
    .pipe(browserify({
      insertGlobals : true,
      debug : !gulp.env.production
    }))
    .on('prebundle', function(bundle) {
      bundle.external('domready');
      bundle.external('react');
    })
    .pipe(gulp.dest('./build/js'))
});

postbundle

.on('postbundle', function(src){})

Event triggered after the bundle process is over and provides the bundled data as an argument to the callback.

License

Copyright (c) 2014 Robo (deepak1556) https://github.com/deepak1556

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

gulp-browserify's People

Contributors

alexgorbatchev avatar andrezsanchez avatar bryant1410 avatar dashed avatar deepak1556 avatar deltaidea avatar download13 avatar joakimbeng avatar pavelgavlik avatar retrofox avatar rikukissa avatar shuhei avatar stephenlacy avatar stonecypher avatar xixixao avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

gulp-browserify's Issues

Blacklisted

Just wanted to share that this plugin has been blacklisted by gulp.js suggesting to use the browserify module directly instead. I haven't dug into what it would mean to just use browserify. If it'd be difficult, perhaps you should open a pull request to take this off the blacklist.

Wrong filename is passed to transform function (jadeify transform fails).

Hi!
I want a simple configuration: require jadeify-ed jade templates in my clientside js code.
In order to get this I've tried to use jadeify transform, which works perfectly in the command line (browserify -t jadeify app.js) with require('template.jade') in app.js.

Buy trying to make it work with gulp-browserify I've found a strange error and cannot guess where actually does it come from.

Trying to use simple transform jadeify in my gulpfile.js:

gulp.task('js', function() {
    gulp.src('client/app.js')
        .pipe(browserify({
            transform: ['jadeify']
        }))
        .pipe(gulp.dest('static'))
});

Jadeify is installed and perfectly require-d, but fails because it gets wrong file name fake_XXXXXX.js instead of template.jade. I've crawled the sources trying to find a fix, but could find nothing.

Maybe module-deps creates such strange filenames?

npm i --save-dev gulp-browserify fails.

npm ERR! Error: No compatible version found: base64-js@'feross/base64-js'
npm ERR! Valid install targets:
npm ERR! ["0.0.1","0.0.2","0.0.3","0.0.4"]

After multiple install attempts, inc deleting the broken node_modules folder.

Base directory for gulp-browserify

Hi! Is there way to set base directory with gulp-browserify

For example I have ./public/coffee/app.coffee file and ./public/coffee/contollers/fileContollr.coffee file

#app.coffee file
require "./controllers/fileController"

when I run gulp from root directory . I have following message

module "./controllers/fileController" not found from "...\\public\\coffee\\app.coffee"

How I could change this behaviour.

Thanks.

Example docs showing how to coffeeify don't work

The example for doing a transform doesn't actually seem to do a transform.

gulp.task('scripts', function() {
    //single entry point to browserify
    gulp.src(['./src/index.coffee'])
        .pipe(browserify({
          transform: ["coffeeify"],
          insertGlobals : true,
          debug : true
        }))
        .pipe(concat('dest.js'))
        .pipe(gulp.dest('./build'))
});

Source of index.coffee:

x = 2
f = (x) -> x + x

The error I get is:

stream.js:94
      throw er; // Unhandled stream error in pipe.
            ^
SyntaxError: Unexpected token >

If I write plain JavaScript in index.coffee, it browserifies it.

I haven't figured out how to actually get the transform working yet; if I figure it out, I'll update this issue.

breaking on errors from some transforms

It seems to be breaking when reporting an error in some cases.
In my case it happens with reactify which is strange because as far as I know this transform should report the syntax errors (I know in grunt the errors from reactify were showing up).

Error: Missing error message
  at new PluginError (/project/node_modules/gulp-util/lib/PluginError.js:54:28)
  at wrapWithPluginError (/project/node_modules/gulp-browserify/index.js:37:10)
  at Stream.<anonymous> (/project/node_modules/gulp-browserify/index.js:96:28)
  at Stream.<anonymous> (/project/node_modules/gulp-browserify/node_modules/browserify/index.js:292:22)
  at Stream.<anonymous> (/project/node_modules/gulp-browserify/node_modules/browserify/index.js:292:22)
  at Stream.EventEmitter.emit (events.js:117:20)
  at Stream.EventEmitter.emit (events.js:117:20)
  at Stream.EventEmitter.emit (events.js:117:20)
  at Stream.EventEmitter.emit (events.js:117:20)
  at Stream.compile (/project/node_modules/reactify/index.js:30:14)
  at _end (/project/node_modules/reactify/node_modules/through/index.js:65:9)
  at Stream.%

TypeError: Arguments to path.join must be strings

Hi,

I'm trying to run gulp-browserify but I get the following error: TypeError: Arguments to path.join must be strings

[gulp] Running 'browserify'...

path.js:360
        throw new TypeError('Arguments to path.join must be strings');
              ^
TypeError: Arguments to path.join must be strings
    at path.js:360:15
    at Array.filter (native)
    at Object.exports.join (path.js:358:36)
    at Stream.endStream (/Users/me/project/node_modules/gulp-concat/index.js:30:27)
    at _end (/Users/me/project/node_modules/gulp-concat/node_modules/through/index.js:65:9)
    at Stream.stream.end (/Users/me/project/node_modules/gulp-concat/node_modules/through/index.js:74:5)
    at Stream.onend (stream.js:79:10)
    at Stream.EventEmitter.emit (events.js:117:20)
    at end (/Users/me/project/node_modules/gulp/node_modules/map-stream/index.js:108:39)
    at queueData (/Users/me/project/node_modules/gulp/node_modules/map-stream/index.js:57:17)
    at next (/Users/me/project/node_modules/gulp/node_modules/map-stream/index.js:68:5)
    at /Users/me/project/node_modules/gulp/node_modules/map-stream/index.js:77:7
    at /Users/me/project/node_modules/gulp/lib/createInputStream/bufferFile.js:7:5
    at fs.js:266:14
    at /Users/me/project/node_modules/gulp/node_modules/graceful-fs/graceful-fs.js:103:5
    at Object.oncomplete (fs.js:107:15)

My Gulpfile browserify task:

gulp.task 'browserify', ['coffee'], ->
  gulp.src('demo/scripts/myproject.js')
    .pipe(browserify({insertGlobals : true, debug: true}).on('error', gutil.log))
    .pipe(concat('myproject-bundle.js'))
    .pipe(gulp.dest('./demo/'))

Any idea what is going on? Thanks!

changing gulp.src seems to break require and/or externals

I am using the require and external options to reduce build times. But things break when I pass browserify files from different directories.

Here is a very simple example.

This works:

gulp.task("vendor", function () {
  return gulp.src("./noop.js", {read:false}) // An empty file to start the stream
    .pipe(browserify({
      require: ["underscore"]
    }))
    .pipe(rename('vendor.js'))
    .pipe(gulp.dest('./build'));
});

gulp.task("app", function () {
  return gulp.src("./app.js", {read:false})
    .pipe(browserify({
      external: ["underscore"]
    }))
    .pipe(gulp.dest('./build'));
});

Result: I can access "underscore" in app.js. Everything works fine.

This doesn't work:

gulp.task("vendor", function () {
  return gulp.src("./noop.js", {read:false}) // An empty file to start the stream
    .pipe(browserify({
      require: ["underscore"]
    }))
    .pipe(rename('vendor.js'))
    .pipe(gulp.dest('./build'));
});

gulp.task("app", function () {
  return gulp.src("./anotherDirectory/app.js", {read:false}) // THIS IS THE ONLY LINE THAT CHANGED!
    .pipe(browserify({
      external: ["underscore"]
    }))
    .pipe(gulp.dest('./build'));
});

Result: I get an error like "Cannot find module 'h15NQi' from app.js.

Should changing the directory have this effect?

browserify require configuration

Is it possible to use the following statement in browserify with gulp-browserify module
browserify({
require : { jquery : 'jquery-browserify' }
});
Basically I want to export 'jquery-browserify' module with name 'jquery'

Currently it throws error when I try to used the above statement with gulp-browserify

Gulp browserify fails silently?

The test.js is in the same directory as my gulpfile.js but for some reason is isn't outputting to tmp.js. The file isn't created.

'use strict';

var _ = require('underscore');

var logUnderscoreVersion = function() {
    console.log(_.VERSION);
};

module.exports = logUnderscoreVersion;
gulp.task('browserify', function() {
    var production = gutil.env.type === 'production';

    gulp.src(['test.js'], {read: false})

        // Browserify, and add source maps if this isn't a production build
        .pipe(browserify({
            debug: true
        }))

        // Rename the destination file
        .pipe(rename('tmp.js'))

        // Output to the build directory
        .pipe(gulp.dest('./'));
});
$ gulp browserify
[gulp] Using gulpfile /home/richard/Code/enrichit-dev/gulpfile.js
[gulp] Starting 'browserify'...
[gulp] Finished 'browserify' after 5.88 ms

Any ideas?

node_modules being included

I know this is no longer maintained, but I hope someone can help.

I'm getting this message: [BABEL] Note: The code generator has deoptimised the styling of "g:/web/money-site/node_modules/jquery/dist/jquery.js" as it exceeds the max of "100KB". When running a gulp task using babelify.

The task is taking 40 seconds, I assume because it's going through node modules; I thought node_modules was ignored by default?

This is my gulp file:

var gulp = require('gulp');
var browserify = require('gulp-browserify');
var babelify = require('babelify');
var rename = require('gulp-rename');

gulp.task('js', function() {
    return gulp.src('app/client.js', { read: false })
        .pipe( browserify({ extensions: ['.jsx'], transform: ['babelify'] }) )
        .pipe( rename('main.js') )
        .pipe( gulp.dest('dist/') )
    ;
});

The owner of babelify says probably not an issue at their end: babel/babelify#79

please update browserify. You're requiring 3.x, the current version is 6.x

This is causing all kinds of problems with bugs that got fixed since the 3.x release of browserify (particularly browserify builds breaking because 3.x had files that didn't pass esprima's quality filters).

Could I ask you up browserify and browserify-shim's versions and push up a new release for gulp-browserify to npm?

browserify+ coffeeify+ preprocess cannot work right.Here's my gulpfile.

I want to transfer the variable of DEMO_NAME to main.coffee.But when comes to browserify, the ouput simply print literally ''/* @echo DEMO_NAME */''. Surely the browserify issues ,right?

gulp.task 'browserify', ->
    options =
        transform: ['coffeeify']
        extensions: ['.coffee']
    gulp.src('./view/coffee/main.coffee', read: false)
        .pipe(plumber(errorHandler: notify.onError("Error: <%= error.message %>")))
        .pipe(browserify(options))
        .pipe(preprocess({context: { NODE_ENV: 'TEST', DEMO_NAME: demoName, DEBUG: true}}))
        .pipe(rename('main.js'))
        .pipe(gulp.dest('test/'))
        .pipe(notify('browserify success!'))
        .pipe(connect.reload())

Restart watch after syntax error?

When using in gulp watch and a syntax error appears in the watched file the whole gulp process dies. Could it be possible to somehow restart the watcher?

Error: need proper browserify instance, on windows machine

Hi,

I have a own seed https://github.com/damirkusar/leptir-angular-seed. When i execute it with gulp, then i get this error message, but just on a windows computer:

Error: browserify-shim needs to be passed a proper browserify instance as the first argument
you passed:โ†[32m'C:\Users\Damir\test\leptir-angular-seed\node_modules\gulp-browserify\node_modules\browserify
node_modules\buffer\index.js'โ†[39m

at preValidate (C:\Users\Damir\test\leptir-angular-seed\node_modules\gulp-browserify\node_modules\browserify-shim\in
dex.js:16:11)
at shim (C:\Users\Damir\test\leptir-angular-seed\node_modules\gulp-browserify\node_modules\browserify-shim\index.js:
83:3)
at nr (C:\Users\Damir\test\leptir-angular-seed\node_modules\gulp-browserify\node_modules\browserify\node_modules\mod
ule-deps\index.js:243:23)
at C:\Users\Damir\test\leptir-angular-seed\node_modules\gulp-browserify\node_modules\browserify\node_modules\resolve
\lib\async.js:42:21
at C:\Users\Damir\test\leptir-angular-seed\node_modules\gulp-browserify\node_modules\browserify\node_modules\resolve
\lib\async.js:121:35
at C:\Users\Damir\test\leptir-angular-seed\node_modules\gulp-browserify\node_modules\browserify\node_modules\resolve
\lib\async.js:93:39
at C:\Users\Damir\test\leptir-angular-seed\node_modules\gulp-browserify\node_modules\browserify\node_modules\resolve
\lib\async.js:59:30
at C:\Users\Damir\test\leptir-angular-seed\node_modules\gulp-browserify\node_modules\browserify\node_modules\resolve
\lib\async.js:18:18
at FSReqWrap.oncomplete (fs.js:95:15)

do you know what that could be?

Support for aliasMapping

Hi,

Do you plan to support aliasMapping like grunt-browserify does? I would definitely use that in my current project. Thanks!

TypeError: Object has no method 'replace'

I am able to browserify my app, but with gulp-browserify ( using the example gulp-configuration ),
i get:

gulperror

My app.js is simply "var x = 1;"
It seems that browserify can not work with the stream.

i am using:

  • Windows 7
  • latest npm, node, gulp-concat, gulp-browserify

Uncaught Error: Cannot find module... browser.js when building on Windows

Consider the following reduced test case:

foo.js

var bar = require('./bar.js');
console.log(bar.message);

bar.js

module.exports.message = "This is a message.";

Using gulp-browserify 0.4.4, with this as my gulpfile:

gulp.task('js', function () {
    var browserify = require('gulp-browserify');
    gulp.src('./js/foo.js')
        .pipe(browserify({
          insertGlobals : true
        }))
        .pipe(gulp.dest('./build/js'))
});

on Windows, the output includes

{"D:\\\\Users\\\\mmartin\\\\Desktop\\\\browserify\\\\node_modules\\\\gulp-browserify\\\\node_modules\\\\browserify\\\\node_modules\\\\insert-module-globals\\\\node_modules\\\\process\\\\browser.js":3,"buffer":4}

And when I try to load the JS file in the browser, I get the following error:

Uncaught Error: Cannot find module 'D:\Users\mmartin\Documents\GitHub\ss14-team-231\node_modules\gulp-browserify\node_modules\browserify\node_modules\insert-module-globals\node_modules\process\browser.js' 

This issue does not exist when building with gulp-browserify 0.4.3. I'm not sure if this is the equivalent line in the compiled output, but if so, it looks like this:

{"./bar.js":1,"__browserify_Buffer":4,"__browserify_process":3}

Has something changed in the way I should be using gulp-browserify with version 0.4.4, or is this a bug?

Run gulp task within transforms option

I just created my own gulp plugin to transpile ES6 modules was wondering if it's possible to run my own plugin inside the transforms option.

I want to be able to do this:

gulp.src('src/entry.js')
  .pipe(browserify({
      transform: [es6ModuleTranspiler({type: 'cjs'})]
      debug: true
  }))
  .pipe(gulp.dest('./dist'));

Where es6ModuleTranspiler is my plugin that is expecting a stream.

Error only when requiring d3

$ gulp

runs fine, everything builds as expected. When the browser tries to run the line:

var d3 = require('d3');

in my app.js file, dev tools reports the following error:

Uncaught Error: Cannot find module '/data/projects/gulpTest/node_modules/gulp-browserify/node_modules/browserify/node_modules/insert-module-globals/node_modules/process/browser.js' 

in _prelude.js. The file .../process/browser.js does, however, exist during the gulp build step.

Notably - when I try requiring other modules (e.g. underscore) that I've installed via npm, I can't reproduce the error.

Possibly helpful information:

$ node --version
> v0.10.20

Installed NPM packages (locally)

"gulp", "3.5.2"  
"gulp-util": "~2.2.14",
"gulp-browserify": "~0.4.4", 
"d3": "~3.4.1"  

gulpfile.js file:

var gulp = require('gulp');
var browserify = require('gulp-browserify');

gulp.task('scripts', function(){

  return gulp.src('src/app.js')
    .pipe(browserify({
        insertGlobals: true,
        debug: true

    }))
      .pipe(gulp.dest('./build/js'));

});

gulp.task('default', ['scripts']);

src/app.js

console.log("Prints output to devtools console successfully");
var d3 = require('d3');
console.log("This will never run");

// a bunch of (probably) irrelevant d3 code...

I'm not sure where I've gone wrong here. Any ideas?

Cheers.

user-specified version of browserify

browserify versions evolve quickly and I like to be able to restrict the version I am using. It would be nice to be able to provide the version of browserify I need, rather than letting the plugin impose it
e.g.

var _browserify = require('browserify');
var browserify = require('gulp-browserify')(_browserify);

Replace *CB with events

Streams are EventEmitters so you can just emit events and people can wire up x listeners to them

Unable to Run Back-to-Back gulp-browserify Tasks

I've inherited a large legacy codebase, and I have decided to implement gulp + browserify for our build step. Unfortunately, due to the way the app was architected, it doesn't make sense to compile everything down to a single app.js file. Instead, I have broken out the compiled files for each of the feature modules.

During my build step, I want to run a gulp task that looks like this:

gulp.task('browserify:build, ['browserify:feature1', 'browserify:feature2', 'browserify:feature3']);

Where each sub-task calls gulp-browserify to compile the javascript to the associated feature module. I should note that all three feature modules as pull in a shared core module.

Unfortunately, after calling the 'browserify:build' task and attempting to run the app, I find that it errors out. For now, I have created a workaround that does this:

gulp.task('browserify:dev', function () {
var exec = require('child_process').exec;
var cmd = 'gulp browserify:feature1; gulp browserify:feature2; gulp browserify:feature3';
exec(cmd);
});

This works, although is not ideal.

Thanks.

Support for option `standalone`

It would be great to have support for browserifies option standalone, so we can create standalone modules.

Right now when I do:

gulp.src('./index.js')
    .pipe(browserify({
      standalone: 'mylib'
    }))
    .pipe(concat('mylib.js'))
    .pipe(gulp.dest('./dist'));

I get an error:

stream.js:94
      throw er; // Unhandled stream error in pipe.
            ^
standalone only works with a single entry point

Make external an available option

Instead of

 .pipe(browserify())
    .on('prebundle', function(bundle) {
      bundle.external('domready');
      bundle.external('react');
    })

enable

 .pipe(browserify(external: ['domready', 'react']))

I am not familiar enough with browserify to be able to tell whether it needs to be changed, there seems to be some resolution magic going on when externals are passed on the command line.

gulp.watch, gulp-browserify, and errors.

Hi, this is not so much a bug as a request for clarification/suggestion from a gulp noob.

gulp-browserify works wonderfully, so much so I have it running in side of a gulp.watch task. However, anytime I cause an error (such as require a file before I create it) the task fails and gulp exits.

For gulp-less I was able to use gulp-plumber to handle the exceptions and keep watching. This did not prove successful with gulp-browserify. Is there a more elegant way to handle this? Possibly something obvious I am missing?

Thanks!

Can't resolve dependencies when .pipe()'d to mocha

Hi Guys,

Thanks for the great plugin, I'm new to gulp so maybe I'm misunderstanding how thing work, but gulp-browserify doesn't seem to respect the shim when I pipe it to mocha(). Here's the relevant parts of my gulpfile.js:

I've got a browserifyShim object that I'm trying to share with my script task and test task:

var browserifyShim = {
  jquery: {
    path: 'app/bower_components/jquery/jquery.min',
    exports: '$'
  },
  /* --- [ jQuery UI WIDGETS ] --- */
  jqueryui: {
    path: 'app/bower_components/jquery.ui/ui/jquery.ui.core',
    exports: 'jqueryui',
    depends: {
      jquery: 'jquery'
    }
  },
  jqueryuiWidget: {
    path: 'app/bower_components/jquery.ui/ui/jquery.ui.widget',
    exports: 'jqueryuiWidget',
    depends: {
      jquery: 'jquery',
      jqueryui: 'jqueryui'
    }
  }
}

I've got a script task, where I use gulp-browserify and pass it my shim. It works just fine:

gulp.task('scripts', function() {
  return gulp.src('app/js/app.js')
    .pipe(jshint('.jshintrc'))
    .pipe(jshint.reporter('default'))
    .pipe(browserify({
      shim: browserifyShim,
      insertGlobals : true,
      debug : !gutil.env.production
    }))
    .pipe(concat('bundle.js'))
    .pipe(gulp.dest('dist/assets/js'))
    .pipe(rename({suffix: '.min'}))
    .pipe(uglify())
    .pipe(gulp.dest('dist/assets/js'))
    .pipe(livereload(server))
    .pipe(notify({ message: 'Scripts task complete' }));
});

But I've also got a test task, where I also try to use gulp-browserify and my browserifyShim object to resolve dependencies. This doesn't work:

gulp.task('test', function() {
  return gulp.src('test/spec/**/*.js')
    .pipe(browserify({
      shim: browserifyShim,
      insertGlobals : true,
      debug : !gutil.env.production
    }))
    .pipe(mocha({
      'ui' : 'bdd'
    }))
   .pipe(notify({ message: 'Test task complete' }));
});

There's only one test, and it looks like this:

'use strict';

var expect = require('chai').expect,
        ui = require('../../app/js/ui/index');

describe("ui", function () {
    it("#example test", function () {
      expect(true).to.be.true;
    });
});

The file at ../../app/js/ui/index loads just fine, but the dependencies that are defined inside of it, which I thought should still resolve through the shim passed to gulp-browserify, don't load properly. Inside of ../../app/js/ui/index I define a single dependency with:

var widget = require('jqueryuiWidget');

This doesn't work when I run my gulp test task, but works just fine when I run gulp scripts. When I run my gulp test task I get Error: Cannot find module 'jquery'

Have I misunderstood how to use the plugin? Thanks for any help!

Trouble with external (multiple bundles)

I'm having trouble setting up multiple bundles. What I am trying to do is have one task to bundle my vendor libraries (vendor.js) and another task to bundle my application logic (main.js).

My vendor task is something like this:

var bower = 'app/bower_components';

// Vendor
gulp.task('vendor', function () {
  return gulp.src([
    bower + '/angular/angular.js',
    bower + '/angular-route/angular-route.js',
    bower + '/lodash/dist/lodash.js'
    ])
    .pipe($.browserify({
      debug: true,
      insertGlobals: true,
      transform: [
        'debowerify'
      ],
      shim: {
        angular: {
          path: bower + '/angular/angular.js',
          exports: 'angular'
        },
        'angular-route': {
          path: bower + '/angular-route/angular-route.js',
          exports: 'ngRoute',
          depends: {
            angular: 'angular'
          }
        },
        lodash: {
          path: bower + '/lodash/dist/lodash.js',
          exports: '_'
        }
      },
      alias: [
        bower + '/angular/angular.js:angular',
        bower + '/angular-route/angular-route.js:angular-route',
        bower + '/lodash/dist/lodash.js:lodash'
      ]
    }))
    .pipe($.concat('vendor.js'))
    // .pipe($.uglify())
    .pipe(gulp.dest('dist/scripts'))
    .pipe($.size());
});

My Scripts task (which should be able to require vendor libraries from the vendor.js bundle above) looks something like this:

// Scripts
gulp.task('scripts', function () {
  return gulp.src('app/scripts/main.js', {read: false})
    .pipe($.browserify({
      debug: true,
      transform: [
        'browserify-jade',
        'debowerify'
      ],
      external: ['angular', 'angular-route', 'lodash'],
      insertGlobals: true,
    })
    .on('prebundle', function(bundle) {
      bundle.external('angular');
      bundle.external('angular-route');
      bundle.external('lodash');
    }))
    // .pipe($.uglify())
    .pipe(gulp.dest('dist/scripts'))
    .pipe($.size())
    .pipe($.connect.reload());
});

When I run the scripts task any external library which should be requirable from vendor.js is still being included inside my main.js bundle. I've tried multiple variations on this (I'm a little unclear what exactly the {read: false} option does. I've also tried playing around with the bundle.external method including the aliased name (ie angular) and the path (app/bower_compontents/angular/angular.js or ./app/bower_compontents/angular/angular.js), but am still getting the vendor libraries bundled into main.js.

Can you please point me in the right direction? I'm able to do something very similar to this in grunt, but am unable to get this working correctly in gulp.

external bundle is replace with an hash

I am trying to declare a module as external like that:

    gulp.src([paths.src + '/main/app/main.js'])
        .pipe(browserify({
            debug: gutil.env.type !== 'production',
            transform: ['reactify'],

            // do not concat react in our javascript, let it external
            // it means that the react javascript must be included in the html
            // with the same version as the react dependency in package.json
            external: ['react']
        }))

Sample app: https://github.com/yanns/react-unit-test/blob/master/gulpfile.js#L39

It kind of works, as the react lib is not concatenated with my application javascript.
But, in the generated javascript, the module name for react is replaced with an hash like that:

"react":"TTpHcX"

leading to an error in the browser: Uncaught Error: Cannot find module 'TTpHcX'

I tried a lot of different configurations, included those found in #55

I tried to define alias, but without any success at the moment.
Is it a problem with gulp-browersify, or with my configuration?

Thanks for any help.

Transforms and Flags

Hey Deepak, interested in your Gulp task :)

Just wanted to know if there is any way of using source transforms and command-line flags with this task? Or is this still in the pipeline for development?

I know you've enabled the option of passing an options object straight to Browserify, but the docs don't specify any means of doing so (other than the extensions flag among a few other options).

Pass browserified code downstream

I'm trying to run jasmine tests on a compiled browserify bundle.

My test looks like this:

require('../main.js') // non-transformed code
describe(...)

But main js contains code that needs to be transformed by browserify, reactify, envify, so I'm trying to browserify before I pass into jasmine:

gulp.src('./test/*')
  .pipe(
    browserify({
      transform: ['reactify', 'envify']
    })
  )
  .pipe(
    jasmine({ verbose: true })
  )

But when it gets to jasmine, the code hasn't been transformed.

semicolon not added to the end of the generated file

I am in the odd situation of needing to concatenate the result of browserify with some other scripts. The file generated by browserify is a self-executing anonymous function, but it doesn't have a semicolon at the end. In my case, it is followed by another parentheses wrapped self executing anonymous function. This causes an "uncaught object" error.

Exclude files from node_modules

Here is what I'm doing with Gulp:

  • creating a dependencies.js file which uses bundle.require to export lodash, d3, ...
  • creating a app.js file which uses bundle.external to tell browserify not to resolve lodash, d3, ...
  • my Gulpfile.js uses lodash for convenience, so it is in my node_modules directory

the app.js file does:

var d3 = require('d3'); // works fine
var lodash = require('lodash'); // error: Cannot find module 'Hze43j'
var lodash = require('' + 'lodash'); // works

The problem is that gulp-browserify tries to be smart during compile-time and tries to replace require('lodash') with a require('Hze43j') which must correspond to node_modules/lodash (which I do not include in my build since I use a bundle.external('lodash')), and does not try to do it when I do the require('' + 'lodash')

Is it possible to tell browserify to not try to modify module names that are declared as external even if they appear in the node_modules directory?

ignore do not support the relative path

Dear,
I find that this ignore options do not support the relative path.
My gulpfile.js code like this:

gulp.task('test', function(){
    return gulp.src('script/modal.js')
        .pipe(browserify({
            //ignore: [./script/jquery.js]     //relative path.  it is invalid!!
            ignore: [require.resolve('./script/jquery.js')] // I need to write like this way 
        }))
        .pipe(gulp.dest('./dist'));
  });

I think it can be write in the source, so that the options can support relative path also
such as

    [
      'exclude',
      'add',
      'external',
      'transform',
      'ignore',
      'require'
    ].forEach( function(method) {
      if (!opts[method]) return;
      [].concat(opts[method]).forEach(function (args) {
        //here args  dispose to a absolute path first.
        bundler[method].apply(bundler, [].concat(args));
      });
    });

Thanks for you time : )

require call with colon throws error

I want to use backbone with lodash instead of underscore and found this howto: jashkenas/backbone#2970

I tried the same with gulp-browserify and the prebundle function

gulp.src('public/js/main.js')
    .pipe(browserify())
    .on('prebundle', function(bundle) {
        bundle.require('lodash:underscore');
    })
    .pipe(gulp.dest('public/dist'));

But i get this error

stream.js:94
throw er; // Unhandled stream error in pipe.
Error: module "lodash:underscore" not found

Any ideas?
Thanks in advance for your help!

Browserify options

Would it be possible to have support for more browserify options and not only the bundle options?

This could be accomplished by modifying the index.js, something like this:

module.exports = function(opts, ctrOpts) {
    var opts = opts || {};
    var ctrOpts = ctrOpts || {};

I really need this to be able to specify builtins and commondir.

uglifyify support

It compresses Browserify without destroying the source-map files.

no-parse breaks shims

When I add a shim and the same file to the noParse option I get Uncaught ReferenceError: global is not defined

This is the gulp-task:

gulp.src('public/js/app.js')
    .pipe(plumber())
    .pipe(browserify({
        insertGlobals: true,
        noParse: "node_modules/phaser/build/phaser.min.js",
        debug: !gulp.env.production,

        shim: {
            phaser: {
                path: 'node_modules/phaser/build/phaser.min.js',
                exports: 'Phaser'
            }
        }

    }))
    .pipe(uglify())
    .pipe(rename('bundle.js'))
    .pipe(gulp.dest('./public/js/'))
    .pipe(livereload(server))
;

Also it still takes ages for the task to complete, so I assume that browserify still parses the file.

Shim unusable with gulp.watch

When using watch the shim wrapper is added x times where x is the number of times the browserify pipe is used. Resulting into broken browserify builds.


This picture shows the output of a build (with shim).

'module' is undefined in browserify_shim__define__module__export__

I tried using the gulp template from https://gist.github.com/simme/8931006. The resulting templates.js file contains this:

(function browserifyShim(module, exports, define, browserify_shim__define__module__export__) {

; global.Handlebars = require("handlebars");
module.exports = Ember.TEMPLATES["index"] = Ember.Handlebars.template(function anonymous(Handlebars,depth0,helpers,partials,data) {
this.compilerInfo = [4,'>= 1.0.0'];
helpers = this.merge(helpers, Ember.Handlebars.helpers); data = data || {};
  data.buffer.push("THIS IS A TEMPLATE!");

});
; browserify_shim__define__module__export__(typeof Ember.TEMPLATES != "undefined" ? Ember.TEMPLATES : window.Ember.TEMPLATES);

}).call(global, undefined, undefined, undefined, function defineExport(ex) { module.exports = ex; });

There is no way this code can execute without error, if I'm reading it correctly, and indeed it fails because it tries to set 'exports' on module, which is undefined. Is this a bug or am I missing something?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.