Prebuild Webpack Plugin

1.1.1 · active · verified Tue Apr 21

Prebuild Webpack Plugin is a utility designed to execute file processing and I/O operations before a webpack build commences. It currently stands at stable version 1.1.1, with a history of steady, active development and releases addressing issues and improving performance. This plugin distinguishes itself by offering dedicated `build` and `watch` hooks that fire before the initial webpack compilation and on subsequent rebuilds, respectively. It supports file matching via minimatch patterns, allowing for targeted pre-processing. A key feature is the ability to explicitly add matched files to webpack's dependency tree and specific handling for complex build environments like Next.js through the `compilationNameFilter` option, enabling users to optimize for client-side or server-side compilations. It is particularly useful for scenarios requiring data transformation or external resource fetching prior to bundling, providing a flexible interface for such tasks.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to integrate `PrebuildPlugin` into a webpack configuration. It sets up `build` and `watch` hooks to process markdown files in the `src` directory before the initial build and upon subsequent changes, logging their content. It also configures file matching and adds matched files as webpack dependencies.

const PrebuildPlugin = require('prebuild-webpack-plugin');
const path = require('path');
const fs = require('fs/promises');

module.exports = {
  // ... webpack config ...
  plugins: [
    new PrebuildPlugin({
      build: async (compiler, compilation, matchedFiles) => {
        console.log('Prebuild phase started!');
        // Example: Read and log content of matched markdown files
        for (const file of matchedFiles) {
          const content = await fs.readFile(file, 'utf8');
          console.log(`Prebuilt content of ${path.basename(file)}:\n${content.substring(0, 100)}...`);
        }
        console.log('Prebuild phase completed!');
      },
      watch: async (compiler, compilation, changedFile) => {
        console.log(`File changed in watch mode: ${changedFile}`);
        // Example: Process the changed file on each rebuild
        if (changedFile.endsWith('.md')) {
          const content = await fs.readFile(changedFile, 'utf8');
          console.log(`Watch-mode processing for ${path.basename(changedFile)}:\n${content.substring(0, 50)}...`);
        }
      },
      files: { 
        pattern: '**/*.md', 
        options: { cwd: path.resolve(__dirname, 'src') }, 
        addFilesAsDependencies: true 
      },
      clearCacheOnUpdate: false
    }),
  ],
};

view raw JSON →