1

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'
},
};
4

1 回答 1

2

有几件事:

  1. 在 karma 中使用主要的 webpack 配置似乎是一种惯用的做事方式。不幸的是,这种方法的一个问题是某些 webpack 插件似乎无法在 karma 中工作,例如 CommonsChunk 和 Define。
  2. ES6-not-compiled 问题与使用旧版本的 karma 和 karma-webpack 有关。请参阅https://github.com/webpack/karma-webpack/issues/129

我的业力配置:

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,
   //....
于 2016-12-21T19:18:52.143 回答