Skip to content

rewire-webpack doesn't work with babel-loader #12

Open
@ryardley

Description

@ryardley

CommonJS syntax works

Currently I have the following karma config:

var webpack = require('webpack');
var RewirePlugin = require('rewire-webpack');
var rewirePlugin = new RewirePlugin();

module.exports = function (config) {

  config.set({
    files: ['mjs/my_test_rewire.js'],

    browsers: ['PhantomJS'],
    frameworks: ['jasmine'],

    preprocessors: {
      'mjs/my_test_rewire.js': ['webpack', 'sourcemap']
    },

    webpack: {
      resolve: {
        extensions: ['', '.js', '.jsx']
      },
      module: {
        loaders: [
          { test: /\.(js|jsx)$/, exclude: /node_modules/,
            loader: require.resolve('babel-loader') + '?optional=runtime' },
        ]
      },
      devtool: 'inline-source-map',
      plugins: [ rewirePlugin ]
    }
  });
};

Running the following karma test:

// my_test_rewire.js
var foo = require('./foo');
var rewire = require('rewire');

var fooRewired = rewire('./foo');
fooRewired.__set__('barText', 'dong!');

describe('Rewire test', function() {
  it('should say bar!', function() {
    expect(fooRewired.doBar()).toEqual('dong!');
  });
});

The test pulls in the following dependency:

// foo.js

var barText = require('./bar');

var foo = {
  doBar:function(){
    return barText;
  }
}

module.exports = foo;

Which pulls in another dependency to be mocked:

// bar.js
module.exports = 'bar!';

Which all works like a charm.

ES6 syntax does not

The problem is our source code is all transpiled using ES6 and ES6 modules. So the following does not work and causes an error:

//my_test_rewire.js

import 'es5-shim';
import 'jasmine-jquery/lib/jasmine-jquery';

import foo from './foo';
import rewire from 'rewire';

var fooRewired = rewire('./foo');
fooRewired.__set__('barText', 'dong!');

describe('Rewire test', function() {
  it('should say bar!', function() {
    expect(fooRewired.doBar()).toEqual('dong!');
  });
});
// foo.js
import barText from './bar';

var foo = {
  doBar:function(){
    return barText;
  }
}

export default foo;
// bar.js
export default 'bar!';

The error returned is:

PhantomJS 1.9.8 (Mac OS X) ERROR
  TypeError: 'undefined' is not an object (evaluating '__webpack_require__.m[module].call')
  at /Users/rudi/teg/teg-site/mjs/my_test_rewire.js:125:0 <- webpack:///~/rewire-webpack/lib/rewire.web.js:10:0
PhantomJS 1.9.8 (Mac OS X): Executed 0 of 0 ERROR (0.142 secs / 0 secs)

Even if the test remains in commonJS syntax the test runs but the rewiring fails. Are there any work arounds here at all until the point at which rewire will work with ES6?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions