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.
npm install --save-dev gulp-postcss
npm install postcss # Required peer dependencypostcss (version ^8.0.0)const postcss = require('gulp-postcss');For ES6 modules:
import gulpPostcss from 'gulp-postcss';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'));
});gulp-postcss is built around several key components:
objectMode: truepostcss-load-config for automatic configuration discoverygulp-sourcemaps for source map preservationConfigure 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.jsProcess 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.from(result.css)file.isNull() returns truefile.isStream() returns trueAutomatic 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'));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:
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:
postcss.config.js in file directoryPostCSS 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 })isProtected object that blocks specific optionsAutomatic 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;
}/**
* 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;
}