or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-karma-babel-preprocessor

Preprocessor to compile ES6 on the fly with babel.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/karma-babel-preprocessor@8.0.x

To install, run

npx @tessl/cli install tessl/npm-karma-babel-preprocessor@8.0.0

index.mddocs/

karma-babel-preprocessor

karma-babel-preprocessor is a Karma plugin that provides on-the-fly ES6/ES2015+ JavaScript compilation using Babel during test execution. It enables developers to write modern JavaScript syntax in their test files and source code while maintaining compatibility with various module systems and testing environments.

Package Information

  • Package Name: karma-babel-preprocessor
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install karma-babel-preprocessor @babel/core @babel/preset-env --save-dev
  • Peer Dependencies: @babel/core v7

Core Imports

The package is automatically loaded by Karma when installed. No direct imports are needed in test files.

Karma configuration:

module.exports = function (config) {
  config.set({
    preprocessors: {
      'src/**/*.js': ['babel'],
      'test/**/*.js': ['babel']
    }
  });
};

Basic Usage

// karma.conf.js
module.exports = function (config) {
  config.set({
    frameworks: ['jasmine'],
    
    files: [
      'src/**/*.js',
      'test/**/*.spec.js'
    ],
    
    preprocessors: {
      'src/**/*.js': ['babel'],
      'test/**/*.spec.js': ['babel']
    },
    
    babelPreprocessor: {
      options: {
        presets: ['@babel/preset-env'],
        sourceMap: 'inline'
      }
    },
    
    browsers: ['Chrome']
  });
};

Architecture

karma-babel-preprocessor follows Karma's plugin architecture pattern with these key components:

  • Plugin Registration: Exports a factory function registered as preprocessor:babel in Karma's plugin system
  • Dependency Injection: Uses Karma's DI pattern to receive configuration, logging, and helper services
  • Processing Pipeline: Integrates into Karma's file preprocessing pipeline, transforming files before test execution
  • Configuration Merging: Hierarchical configuration system supporting base config, custom config, and per-file functions
  • Error Handling: Graceful error handling with detailed logging and callback-based error reporting

The plugin acts as a bridge between Karma's preprocessing system and Babel's transformation engine, handling configuration merging and error management.

Capabilities

Babel Preprocessor Registration

The package registers a Karma preprocessor plugin that integrates with Karma's preprocessing pipeline.

/**
 * Main module export that registers the babel preprocessor with Karma
 */
module.exports = {
  'preprocessor:babel': ['factory', createPreprocessor]
};

Preprocessor Factory Function

Creates a Babel preprocessor instance with dependency injection.

/**
 * Factory function that creates a babel preprocessor instance
 * @param {Object} args - Config object of custom preprocessor
 * @param {Object} config - Config object of babelPreprocessor
 * @param {Object} logger - Karma's logger instance
 * @param {Object} helper - Karma's helper functions
 * @returns {Function} Preprocessor function for processing files
 */
function createPreprocessor(args, config, logger, helper): Function;

The dependency injection configuration:

createPreprocessor.$inject = [
  'args', 
  'config.babelPreprocessor', 
  'logger', 
  'helper'
];

File Processing Function

The core preprocessing function that transforms JavaScript files using Babel.

/**
 * Processes a JavaScript file through Babel transformation
 * @param {string} content - File content to process
 * @param {Object} file - Karma file object with originalPath and path properties
 * @param {Function} done - Callback function (error, result)
 * @returns {void} Calls done callback with transformed code or error
 */
function preprocess(content, file, done): void;

The file object structure:

interface KarmaFile {
  /** Original file path */
  originalPath: string;
  /** Current file path (may be modified by preprocessor) */
  path: string;
}

Configuration Options Merger

Merges base and custom configuration options for Babel transformation.

/**
 * Merges configuration options for Babel transformation
 * @param {Object} customConfig - Custom preprocessor config
 * @param {Object} baseConfig - Base babelPreprocessor config
 * @param {Object} helper - Karma helper functions
 * @param {Object} file - File being processed
 * @returns {Object} Merged Babel options
 */
function createOptions(customConfig, baseConfig, helper, file): Object;

Per-File Options Processor

Processes function-based configuration options for per-file customization.

/**
 * Processes function-based configuration options for per-file customization
 * @param {Object} config - Configuration object
 * @param {Object} helper - Karma helper functions
 * @param {Object} file - File being processed
 * @returns {Object} Per-file options object
 */
function createPerFileOptions(config, helper, file): Object;

Configuration

Standard Configuration

Configure the preprocessor in your Karma configuration file:

module.exports = function (config) {
  config.set({
    preprocessors: {
      'src/**/*.js': ['babel'],
      'test/**/*.js': ['babel']
    },
    
    babelPreprocessor: {
      options: {
        presets: ['@babel/preset-env'],
        plugins: ['@babel/plugin-transform-runtime'],
        sourceMap: 'inline'
      }
    }
  });
};

Per-File Function Configuration

Use functions for dynamic per-file configuration:

module.exports = function (config) {
  config.set({
    babelPreprocessor: {
      options: {
        presets: ['@babel/preset-env']
      },
      filename: function (file) {
        return file.originalPath.replace(/\.js$/, '.es5.js');
      },
      sourceFileName: function (file) {
        return file.originalPath;
      }
    }
  });
};

Custom Preprocessor Configuration

Create named custom preprocessors extending the babel preprocessor:

module.exports = function (config) {
  config.set({
    preprocessors: {
      'src/**/*.js': ['babelSourceMap'],
      'test/**/*.js': ['babelTypeScript']
    },
    
    customPreprocessors: {
      babelSourceMap: {
        base: 'babel',
        options: {
          presets: ['@babel/preset-env'],
          sourceMap: 'inline'
        }
      },
      babelTypeScript: {
        base: 'babel',
        options: {
          presets: ['@babel/preset-env', '@babel/preset-typescript']
        },
        filename: function (file) {
          return file.originalPath.replace(/\.ts$/, '.js');
        }
      }
    }
  });
};

Configuration Options

Standard Babel Options

All standard Babel options are supported through the options property:

interface BabelOptions {
  /** Array of Babel presets to apply */
  presets?: string[] | Array<[string, object]>;
  /** Array of Babel plugins to apply */
  plugins?: string[] | Array<[string, object]>;
  /** Source map generation ('inline', true, false, or object) */
  sourceMap?: boolean | 'inline' | 'both' | 'hidden' | object;
  /** Output filename for the transformed code */
  filename?: string;
  /** Source filename for source maps */
  sourceFileName?: string;
  /** Additional Babel transformation options */
  [key: string]: any;
}

Per-File Function Options

Configuration options that accept functions for per-file customization:

interface PerFileOptions {
  /** Function to determine output filename per file */
  filename?: (file: KarmaFile) => string;
  /** Function to determine source filename per file */
  sourceFileName?: (file: KarmaFile) => string;
  /** Any other Babel option as a function */
  [optionName: string]: (file: KarmaFile) => any;
}

Configuration Structure

The complete configuration structure:

interface BabelPreprocessorConfig {
  /** Standard Babel options object */
  options?: BabelOptions;
  /** Per-file function-based options */
  [key: string]: ((file: KarmaFile) => any) | BabelOptions;
}

interface CustomPreprocessorConfig extends BabelPreprocessorConfig {
  /** Must be 'babel' to extend babel preprocessor */
  base: 'babel';
}

Error Handling

The preprocessor handles Babel transformation errors gracefully:

  • Catches all Babel transformation errors
  • Logs errors with file path context using Karma's logger
  • Returns errors through the callback mechanism
  • Validates per-file function configuration and throws descriptive errors

Common error scenarios:

// Per-file option validation error
throw new Error('Per-file option "filename" must be a function.');

// Babel transformation errors are caught and logged:
log.error('%s\n at %s', e.message, file.originalPath);

Integration Notes

Karma Plugin System

The package integrates with Karma's plugin architecture:

  • Automatically discovered when installed (name starts with karma-)
  • Uses dependency injection pattern for configuration and services
  • Registers as preprocessor:babel in Karma's plugin registry

Module System Compatibility

The preprocessor works with various module systems by transforming ES6 modules to:

  • CommonJS (default)
  • AMD
  • SystemJS
  • UMD

Configure module transformation via Babel presets and plugins.

Polyfill Support

For polyfill support, include them in Karma's files configuration:

module.exports = function (config) {
  config.set({
    files: [
      'node_modules/@babel/polyfill/dist/polyfill.js',
      'src/**/*.js',
      'test/**/*.js'
    ]
  });
};