awesome-ts-loader doesn't correctly process files when loaded through karma-webpack

485 views Asked by At

I have an Angular 2 application that is bundled with Webpack, and tested with Jasmine through Karma with karma-webpack. When developing, the code is bundled and served correctly. When testing, awesome-ts-loader throws a "Module parse failed" error on my .spec.ts file.

Module parse failed: /Users/kyleburke/angular2-app/app/main/app.component.spec.ts Unexpected token (10:8)
You may need an appropriate loader to handle this file type.
| ////////  SPECS  /////////////
| describe('AppComponent', function () {
|   let de: DebugElement;
|   let comp: AppComponent;
|   let fixture: ComponentFixture<AppComponent>;
@ ./app \.spec\.ts
@ ./karma-shim.js

I'm using the karma-webpack "alternative method" described on their Github Readme to load all of my .spec files (in karma-shim.js):

var appContext = require.context('./app', true, /\.spec\.ts/);
appContext.keys().forEach(function(path) {
  try {
    appContext(path);
  }
  catch(err) {
    console.error('problem with'+ path);
    console.error(err);
  }
});

The relevant section of my karma.conf.js is configured correctly, according to several sample repos:

files: [
  { pattern: './karma-shim.js', watched: false }
],
preprocessors: {
  './karma-shim.js': ['webpack', 'sourcemap']
},
webpack: webpackConfig,

And everything in my Webpack config lines up (partial sample):

module.exports = () => {
  const TARGET = process.env.npm_lifecycle_event;

  const isTest = TARGET === 'test';

  let config = {};

  config.entry = isTest ? {} : './app/main.ts';

  config.output = isTest ? {} : {
    path: './dist',
    filename: 'bundle.js'
  };

  config.resolve = {
    extensions: ['.ts', '.js', '.json', '.html']
  };

  config.module = {
    rules: [
      {
        test: /\.ts$/,
        loaders: ['awesome-typescript-loader', 'angular2-template-loader' ],
        exclude: [isTest ? /\.(e2e)\.ts$/ : /\.(spec|e2e)\.ts$/, /node_modules\/(?!(ng2-.+))/]
      },
      {test: /\.json$/, loader: 'json-loader'},
      {test: /\.html$/, loader: 'raw-loader'}
    ]
  };

  ...
}

The error from tslint makes me think that Webpack is correctly finding the spec file, but it maybe isn't being handed off to awesome-ts-loader, or it isn't loading the tsconfig.json. (again, everything loads fine when developing).

0

There are 0 answers