Conditional Preprocessor for Webpack

1.0.2 · abandoned · verified Tue Apr 21

if-loader is a webpack module bundler preprocessor that enables C-style conditional compilation using 'if' directives within JavaScript source files. It allows developers to include or exclude blocks of code based on predefined conditions, similar to the `#ifdef` mechanism in C/C++. The current stable version is 1.0.2. This package is no longer maintained, with its last commit dating back over nine years, indicating it is abandoned. While it offers a straightforward way to manage code variants for different build environments, more actively maintained alternatives exist that provide similar or enhanced functionality and better integration with modern webpack features and tooling. Its primary differentiation was its minimalist approach to conditional code exclusion using comment-based directives.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates configuring `if-loader` in `webpack.config.js` to conditionally include or exclude code blocks in `app.js` based on environment variables passed as options to the loader. This allows generating different bundles from the same source code.

/* webpack.config.js */
const path = require('path');

module.exports = {
  mode: 'development',
  entry: './src/app.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js',
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: [
          {
            loader: 'if-loader',
            options: {
              'version-a': process.env.BUILD_ENV === 'alpha',
              'version-b': process.env.BUILD_ENV === 'beta',
              'version-c': true // Always enabled
            },
          },
        ],
      },
    ],
  },
};

/* src/app.js */
console.log('Common code.');

/* #if version-a */
console.log('This is for version-a build.');
/* #end */

// #if version-b
console.log('This is for version-b build.');
// #end

/* #if version-a,version-c */
console.log('This is for version-a OR version-c build.');
/* #end */

// #if version-d
console.log('This will never be included.');
// #end


// To run:
// BUILD_ENV=alpha webpack --config webpack.config.js
// BUILD_ENV=beta webpack --config webpack.config.js
// webpack --config webpack.config.js (for version-c only)

view raw JSON →