What is the correct pattern for using webpack with karma?

2.5k views Asked by At

The official docs seem to imply that you need to duplicate the webpack configuration---once when used outside of the tests, and again inside of karma.conf.

// Karma configuration
module.exports = function(config) {
  config.set({
    webpack: {
    // same webpack config used externally
  },
};

However, when I started to copy/paste the working webpack config, I started to get errors. For example, ES6 code wasn't transpiled (even though babel is configured). The commons chunk plugin wouldn't work as it gave an error. The karma.conf is shown below:

const webpack = require('webpack');

module.exports = function(config) {
 config.set({

// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',

files: [
  'test.webpack.js' //just load this file
],
preprocessors: {
  'test.webpack.js': [ 'webpack', 'sourcemap' ] //preprocess with webpack and our sourcemap loader
},
webpack: {
  module: {
    loaders: [
      {
        test: /\/js\/.+\.js$/,
        exclude: /node_modules/,
        loader: "babel-loader",
        query: {
          presets: ['es2015', 'react'],
          plugins: [
            'transform-es2015-destructuring',
            'transform-object-rest-spread'
          ]
        }
      },
    ],
  },

  resolve: {
    modulesDirectories: ['node_modules'],
  },
  plugins: [
    new webpack.optimize.CommonsChunkPlugin({
      filename: "commons.js",
      name: "commons"
    }),
    new webpack.ProvidePlugin({
      'Promise': 'bluebird',
    })
  ],
  devtool: 'inline-source-map'
},
};
1

There are 1 answers

1
U Avalos On

There are several things:

  1. Using the main webpack config in karma seems to be one idiomatic way of doing things. Unfortunately, one problem with this approach is that certain webpack plugins don't seem to work in karma, for example, CommonsChunk and Define.
  2. The ES6-not-compiled issue was related to using an older version of karma and karma-webpack. See https://github.com/webpack/karma-webpack/issues/129.

My karma config:

const webpackConfig = require('./webpack.config');
const webpack = require('webpack');

webpackConfig.entry = undefined;
webpackConfig.output = undefined;
// tell webpack to ignore these files
webpackConfig.module.loaders.push([
{
  test: /\.(jpe?g|png|gif|svg|map|css|std|indent|html|txt)$/i,
  loader: 'ignore-loader',
},
]);
// karma is actually very brittle. The commons chunk plugin as well as the define plugin break it, so we
// disable these
webpackConfig.plugins = webpackConfig.plugins
  .filter(p => !(p instanceof webpack.optimize.CommonsChunkPlugin))
  .filter(p => !(p instanceof webpack.DefinePlugin));
webpackConfig.devtool = 'inline-source-map';

module.exports = function(config) {
config.set({
   webpack: webpackConfig,
   //....