Skip to content

Arnesfield/rollup-plugin-edit

Repository files navigation

rollup-plugin-edit

npm Node.js CI

A Rollup plugin to edit generated file contents.

Install

npm install rollup-plugin-edit --save-dev

Usage

// ESM
import edit from 'rollup-plugin-edit';

// CommonJS
const { edit } = require('rollup-plugin-edit');

Use the plugin:

// rollup.config.js
import edit from 'rollup-plugin-edit';

export default {
  input: 'src/index.js',
  output: { dir: 'dist' },
  plugins: [edit(/* plugin options */)]
};

Options

You can pass an options object to edit with the following properties:

disabled

Type: boolean

Disable plugin and prevent firing chunk and asset callbacks.

chunk

Type: (data: ChunkData) => MaybePromise<OutputChunk['code'] | null | void>

Handle output chunks.

If a string is returned, it will be used to replace the generated file contents. Otherwise, the file contents remain unchanged.

asset

Type: (data: AssetData) => MaybePromise<OutputAsset['source'] | null | void>

Handle output assets.

If a string or Uint8Array is returned, it will be used to replace the generated file contents. Otherwise, the file contents remain unchanged.

Example

Both chunk and asset callbacks are fired with a parameter, ChunkData and AssetData respectively.

You can get the generated file name through data.fileName and its contents with data.contents.

Tip

See src/types.ts for other properties included in ChunkData and AssetData.

You can set the callbacks and return a value to replace the file's contents.

// rollup.config.js
import edit from 'rollup-plugin-edit';

export default {
  input: 'src/index.js',
  output: [
    { file: 'dist/file1.js', sourcemap: true },
    { file: 'dist/file2.js', sourcemap: true }
  ],
  plugins: [
    edit({
      chunk(data) {
        // modify file1.js but keep file2.js contents
        if (data.fileName === 'file1.js') {
          return data.contents + '// Hello World!\n';
        }
      },
      asset(data) {
        // modify file1.js.map but keep file2.js.map contents
        if (data.fileName === 'file1.js.map') {
          // return a string or Uint8Array
          return Buffer.from('{"file":"file1.js"}');
        }
      }
    })
  ]
};

License

Licensed under the MIT License.