or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-gulp-postcss

PostCSS gulp plugin that pipes CSS through multiple PostCSS plugins while parsing CSS only once for optimal performance

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/gulp-postcss@10.0.x

To install, run

npx @tessl/cli install tessl/npm-gulp-postcss@10.0.0

index.mddocs/

gulp-postcss

gulp-postcss is a Gulp plugin that integrates PostCSS processing into Gulp build workflows, enabling developers to pipe CSS through multiple PostCSS plugins while parsing CSS only once for optimal performance. It provides comprehensive features including automatic configuration loading, source map integration, and flexible plugin configuration options.

Package Information

  • Package Name: gulp-postcss
  • Package Type: npm
  • Language: JavaScript (Node.js)
  • Node.js Requirement: >=18
  • Installation:
    npm install --save-dev gulp-postcss
    npm install postcss  # Required peer dependency
  • Peer Dependencies: postcss (version ^8.0.0)

Core Imports

const postcss = require('gulp-postcss');

For ES6 modules:

import gulpPostcss from 'gulp-postcss';

Basic Usage

const gulp = require('gulp');
const postcss = require('gulp-postcss');
const autoprefixer = require('autoprefixer');
const cssnano = require('cssnano');

gulp.task('css', function () {
    const plugins = [
        autoprefixer({ overrideBrowserslist: ['last 1 version'] }),
        cssnano()
    ];
    return gulp.src('./src/*.css')
        .pipe(postcss(plugins))
        .pipe(gulp.dest('./dest'));
});

Architecture

gulp-postcss is built around several key components:

  • Transform Stream: Creates a Node.js Transform stream for Gulp pipelines with objectMode: true
  • Configuration Loader: Integrates with postcss-load-config for automatic configuration discovery
  • Source Map Handler: Automatic integration with gulp-sourcemaps for source map preservation
  • Error Handler: Specialized error handling for CSS syntax errors and processing failures
  • File Processor: Handles different Vinyl file types (Buffer, Stream, Null) appropriately

Capabilities

Plugin Configuration

Configure PostCSS plugins using multiple approaches for maximum flexibility.

/**
 * Create PostCSS gulp plugin with array of plugins
 * @param plugins - Array of PostCSS plugin functions or plugin objects
 * @param options - PostCSS processing options
 * @returns Transform stream for Gulp pipelines
 */
function postcss(plugins: Array<PostCSSPlugin>, options?: ProcessingOptions): Transform;

/**
 * Create PostCSS gulp plugin with callback configuration
 * @param callback - Function receiving Vinyl file, returns configuration object
 * @returns Transform stream for Gulp pipelines
 */
function postcss(callback: (file: VinylFile) => ConfigObject): Transform;

/**
 * Create PostCSS gulp plugin with configuration object
 * @param configOptions - Options for postcss-load-config
 * @returns Transform stream for Gulp pipelines
 */
function postcss(configOptions?: LoadConfigOptions): Transform;

/**
 * Create PostCSS gulp plugin with automatic configuration loading
 * @returns Transform stream for Gulp pipelines
 */
function postcss(): Transform;

Usage Examples:

// Array of plugins
const plugins = [autoprefixer(), cssnano()];
gulp.src('*.css').pipe(postcss(plugins));

// Callback configuration
gulp.src('*.css').pipe(postcss((file) => {
    return {
        plugins: getPluginsForFile(file),
        options: { syntax: file.extname === '.scss' ? 'scss' : false }
    };
}));

// Configuration object
gulp.src('*.css').pipe(postcss({ config: './postcss.config.js' }));

// Automatic configuration loading
gulp.src('*.css').pipe(postcss()); // Loads from postcss.config.js

File Processing

Process different types of Vinyl file objects with appropriate handling.

interface Transform {
    /** Transform function called for each file in the stream */
    _transform(file: VinylFile, encoding: string, callback: Function): void;
}

File Type Handling:

  • Buffer files: Processed normally, contents transformed using Buffer.from(result.css)
  • Null files: Passed through unchanged when file.isNull() returns true
  • Stream files: Immediately rejected with PluginError when file.isStream() returns true

Source Map Integration

Automatic integration with gulp-sourcemaps for source map preservation.

/**
 * Source map options automatically configured based on file.sourceMap presence
 */
interface AutoSourceMapOptions {
    /** Automatically set to false when gulp-sourcemaps detected */
    annotation: false;
    /** Generated separately for gulp-sourcemaps integration */
    inline: false;
}

Usage with gulp-sourcemaps:

const sourcemaps = require('gulp-sourcemaps');

gulp.src('./src/*.css')
    .pipe(sourcemaps.init())
    .pipe(postcss(plugins))
    .pipe(sourcemaps.write('.'))  // Write source maps to separate files
    .pipe(gulp.dest('./dest'));

Error Handling

Comprehensive error handling for different failure scenarios.

/**
 * CSS Syntax Error handling with enhanced error information
 */
interface CssSyntaxErrorOptions {
    fileName: string;
    lineNumber: number;
    showStack: false;
    showProperties: false;
    error: CssSyntaxError;
}

/**
 * General processing error handling
 */
interface ProcessingErrorOptions {
    fileName: string;
    showStack: true;
}

/**
 * Stream file error handling
 */
interface StreamErrorOptions {
    fileName: string;
    showStack: true;
    message: "Streams are not supported!";
}

Error Types:

  1. CSS Syntax Errors: Enhanced with line numbers and source code context
  2. Processing Errors: General plugin processing failures
  3. Stream File Errors: Rejection of unsupported stream files

Configuration Loading

Integration with postcss-load-config for automatic configuration discovery.

/**
 * Configuration loading options
 */
interface LoadConfigOptions {
    /** Path to configuration file (absolute or relative to file.base) */
    config?: string;
    /** Additional context options passed to postcss-load-config */
    [key: string]: any;
}

/**
 * Configuration object returned by callback functions
 */
interface ConfigObject {
    /** Array of PostCSS plugins to apply */
    plugins: Array<PostCSSPlugin>;
    /** PostCSS processing options */
    options?: ProcessingOptions;
}

Configuration Resolution:

  • Default: Searches for postcss.config.js in file directory
  • Custom path: Uses specified config file path
  • Callback: Dynamic configuration per file

Processing Options

PostCSS processing options with automatic defaults and protection for source maps.

/**
 * PostCSS processing options
 */
interface ProcessingOptions {
    /** Input file path (automatically set to file.path) */
    from?: string;
    /** Output file path (automatically set to file.path, can be overridden) */
    to?: string;
    /** Source map configuration (automatically managed with gulp-sourcemaps) */
    map?: boolean | object;
    /** Custom syntax parser */
    syntax?: object;
    /** Custom CSS parser */
    parser?: Function | object;
    /** Custom CSS stringifier */
    stringifier?: Function | object;
    /** Additional PostCSS options */
    [key: string]: any;
}

Option Protection: When file.sourceMap is detected (gulp-sourcemaps integration):

  • from option cannot be overridden (logs warning and keeps default file.path)
  • map option cannot be overridden (logs warning and keeps { annotation: false })
  • Protection implemented via isProtected object that blocks specific options

Logging and Warnings

Automatic logging of PostCSS warnings and configuration conflicts.

/**
 * Warning display using fancy-log
 * All log messages use file.relative for brevity
 */
interface WarningLogger {
    /** 
     * Log PostCSS processing warnings (only when warnings exist)
     * Format: "gulp-postcss: {file.relative}\\n{warnings}"
     */
    logWarnings(file: VinylFile, warnings: string): void;
    /** 
     * Log configuration override conflicts when using gulp-sourcemaps
     * Format: "gulp-postcss: {file.relative}\\nCannot override {option} option, because it is required by gulp-sourcemaps"
     */
    logConfigConflict(file: VinylFile, option: string): void;
}

Types

/**
 * Vinyl file object used in Gulp streams
 */
interface VinylFile {
    /** File path */
    path: string;
    /** File base directory */
    base: string;
    /** File directory */
    dirname: string;
    /** Relative file path */
    relative: string;
    /** File contents as Buffer or Stream */
    contents: Buffer | Stream | null;
    /** Source map object when using gulp-sourcemaps */
    sourceMap?: object;
    /** Check if file is null */
    isNull(): boolean;
    /** Check if file is stream */
    isStream(): boolean;
    /** Check if file is buffer */
    isBuffer(): boolean;
}

/**
 * PostCSS plugin function or object
 */
type PostCSSPlugin = Function | object;

/**
 * Node.js Transform stream for Gulp pipelines
 */
interface Transform {
    /** Object mode enabled for Vinyl file processing */
    objectMode: true;
    /** Transform function for processing files */
    _transform(file: VinylFile, encoding: string, callback: Function): void;
}