replace-attribute-loader

Replaces the specified attributes with an optional value

Usage no npm install needed!

<script type="module">
  import replaceAttributeLoader from 'https://cdn.skypack.dev/replace-attribute-loader';
</script>

README

replace-attribute-loader

Replaces the specified attributes with an optional value

Table of Contents

  1. Install
  2. Introduction
  3. Get started
  4. Configuration

Install

Install with npm:

npm install --save-dev replace-attribute-loader

Install with yarn:

yarn add replace-attribute-loader --dev

Introduction

replace-attribute-loader enables you to replace attributes from your source code. For example when you have test attributes that you do not want in a production build. This loader can be configured to replace one or more attributes, optionally with a new value.

TL;DR

  • Replace attributes
  • Optional replacement values
  • Easy configuration

Get started

Open the webpack configuration file in which you have specified the loaders. Add the loader wherever you like.

Example 1:

module.exports = {
    ...,

    module: {
        rules: [
          {
            test: /\.tsx?$/,
            use: [
              {
                loader: 'replace-attribute-loader',
                options: {
                  attribute: 'data-test-hook',
                },
              },
            ],
          },
        ]
    }
};

Configuration

Options can be specified in multiple ways.

Example 1: removes all occurrences of 'data-test-hook'

module.exports = {
    ...,

    module: {
        rules: [
          {
            test: /\.tsx?$/,
            use: [
              {
                loader: 'replace-attribute-loader',
                options: {
                  attribute: 'data-test-hook',
                },
              },
            ],
          },
        ]
    }
};



Example 2: removes all occurrences of 'data-test-hook' and 'data-test'

module.exports = {
    ...,

    module: {
        rules: [
          {
            test: /\.tsx?$/,
            use: [
              {
                loader: 'replace-attribute-loader',
                options: {
                  attribute: ['data-test-hook', 'data-test'],
                },
              },
            ],
          },
        ]
    }
};



Example 3: replaces all occurrences of 'data-test-hook' and 'data-test' with the specified value

module.exports = {
    ...,

    module: {
        rules: [
          {
            test: /\.tsx?$/,
            use: [
              {
                loader: 'replace-attribute-loader',
                options: {
                  attribute: {
                    'data-test-hook': 'data-foo="bar"',
                    'data-test': 'data-foo="bar"',
                  },
                },
              },
            ],
          },
        ]
    }
};