nikku / karma-browserify

A fast Browserify integration for Karma that handles large projects with ease
MIT License
321 stars 50 forks source link

external requires lost in new browserify bundle trigger by edit when autoWatch=true #195

Closed crawlregister closed 8 years ago

crawlregister commented 8 years ago

I created a simple example to show the problem I encountered. There is an external module must be required at creating the bundle with browserify.

My karma.conf.js is like this:

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine', 'browserify'],

    // list of files / patterns to load in the browser
    files: [
        'main.js',
        'test.js'
    ],

    // list of files to exclude
    exclude: [],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
        './main.js': ['browserify']
    },

    browserify: {
        debug: true,
        extensions: ['.js'],
        require: ['moment']
    },

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

There is an external require specified as require: ['moment'] The first time run karma start, the moment module is included in the bundle correctly. Then I edit the main.js and save, which will trigger rebundle. But in the new bundle, moment module is missing from the new bundle.

chrisdeely commented 8 years ago

I have found a workaround for this behavior using the configure function & prebundle event in the config block:

browserify: {
      config:{
        watchify: {
          poll: true
        }
      },
      configure: function(bundle) {
        bundle.on('prebundle', function() {
          bundle.require('./path/to/appConfig', {expose: 'appConfig'});
        });
      }
    }

You may be able to execute bundle.require('moment') with or without the expose setting.

Please let me know if that helps

crawlregister commented 8 years ago

Thanks @chrisdeely I will give it a try.

Another potential solution is build the external requires into another bundle and make sure it is ready before running karma test.

nikku commented 8 years ago

Browserify has some strange behavior around externals and stuff.

The working way of consistently exposing moment from outside the bundle is:

  ...
  browserify: {
    configure: function(bundle) {
      bundle.require('moment');
    }
  }

I am happy to accept PRs if you would like to contribute an improvement here.