Unplugin Utilities

0.3.1 · active · verified Sun Apr 19

unplugin-utils is a lean, platform-agnostic library providing essential utility functions specifically designed for developing 'unplugins'—plugins that aim for universal compatibility across various JavaScript bundlers like Vite, Webpack, Rollup, and esbuild. It offers common helpers such as `createFilter` for efficient file path inclusion/exclusion matching and `normalizePath` for consistent path handling across different operating systems. The current stable version is 0.3.1, and the project is actively maintained with frequent minor updates and occasional breaking changes. Its key differentiators include a focus on platform agnosticism (supporting browser and Node.js environments), a smaller bundle footprint compared to alternatives due to a carefully selected subset of functionalities, and a commitment to 100% test coverage. The library is heavily inspired by and incorporates concepts from `@rollup/pluginutils` but is tailored for broader 'unplugin' ecosystem needs.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a basic unplugin using `createFilter` and `normalizePath` to conditionally transform code based on file paths.

import { createFilter, normalizePath } from 'unplugin-utils';
import type { UnpluginBuildContext, UnpluginOptions } from 'unplugin';

interface MyPluginOptions {
  include?: string | RegExp | (string | RegExp)[];
  exclude?: string | RegExp | (string | RegExp)[];
  enable?: boolean;
}

export default function myUnplugin(options: MyPluginOptions = {}): UnpluginOptions {
  const filter = createFilter(options.include, options.exclude);

  return {
    name: 'my-custom-unplugin',
    buildStart(this: UnpluginBuildContext) {
      if (!options.enable) {
        this.warn('My plugin is disabled.');
        return;
      }
      console.log('My Unplugin build started!');
    },
    transform(code: string, id: string) {
      const normalizedId = normalizePath(id);
      if (!filter(normalizedId)) {
        return null; // Skip transformation if id does not match filter
      }

      // Example transformation: prepend a comment
      const transformedCode = `// Transformed by my-custom-unplugin\n${code}`;
      console.log(`Transformed file: ${normalizedId}`);
      return transformedCode;
    },
    buildEnd() {
      console.log('My Unplugin build ended!');
    }
  };
}

view raw JSON →