or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/npm-rollup-plugin-postcss

Seamless integration between Rollup and PostCSS with support for CSS modules, preprocessors, and flexible output options

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/rollup-plugin-postcss@4.0.x

To install, run

npx @tessl/cli install tessl/npm-rollup-plugin-postcss@4.0.0

0

# Rollup Plugin PostCSS

1

2

Rollup Plugin PostCSS provides seamless integration between Rollup and PostCSS, enabling developers to process CSS files with PostCSS plugins during the bundling process. It supports various CSS preprocessors (Sass, Stylus, Less), offers CSS modules functionality, provides options for CSS extraction or injection, includes source map support, and enables advanced features like CSS minimization and custom loaders.

3

4

## Package Information

5

6

- **Package Name**: rollup-plugin-postcss

7

- **Package Type**: npm

8

- **Language**: JavaScript

9

- **Installation**: `npm install rollup-plugin-postcss postcss --dev`

10

11

## Core Imports

12

13

```javascript

14

import postcss from 'rollup-plugin-postcss';

15

// Type definitions (if using TypeScript)

16

import type { PostCSSPluginConf } from 'rollup-plugin-postcss';

17

```

18

19

For CommonJS:

20

21

```javascript

22

const postcss = require('rollup-plugin-postcss');

23

```

24

25

## Basic Usage

26

27

```javascript

28

// rollup.config.js

29

import postcss from 'rollup-plugin-postcss';

30

31

export default {

32

plugins: [

33

postcss({

34

plugins: []

35

})

36

]

37

};

38

```

39

40

Then import CSS files in your JavaScript:

41

42

```javascript

43

import './style.css'; // Injects CSS to <head>

44

import styles from './style.module.css'; // CSS modules

45

```

46

47

## Architecture

48

49

Rollup Plugin PostCSS is built around several key components:

50

51

- **Plugin Factory**: Main export function that creates a Rollup plugin instance

52

- **Loader System**: Modular loaders for different file types (PostCSS, Sass, Stylus, Less)

53

- **Options Processing**: Comprehensive configuration system for all features

54

- **CSS Processing**: PostCSS integration with plugin support and configuration loading

55

- **Output Management**: Flexible CSS injection or extraction with source map support

56

57

## Capabilities

58

59

### Plugin Factory

60

61

Creates a Rollup plugin instance with comprehensive PostCSS processing capabilities.

62

63

```javascript { .api }

64

/**

65

* Creates a Rollup plugin for PostCSS processing

66

* @param options - Configuration options for the plugin

67

* @returns Rollup plugin object

68

*/

69

function postcss(options?: Readonly<PostCSSPluginConf>): Plugin;

70

71

// Required imports for TypeScript usage

72

type FunctionType<T = any, U = any> = (...args: readonly T[]) => U;

73

type CreateFilter = import('rollup-pluginutils').CreateFilter;

74

75

interface PostCSSPluginConf {

76

/** Inject CSS as <style> to <head> */

77

inject?: boolean | Record<string, any> | ((cssVariableName: string, id: string) => string);

78

/** Extract CSS to file */

79

extract?: boolean | string;

80

/** Callback when CSS is extracted */

81

onExtract?: (asset: OnExtractAsset) => boolean;

82

/** Enable CSS modules */

83

modules?: boolean | Record<string, any>;

84

/** File extensions to process */

85

extensions?: string[];

86

/** Note: Present in TypeScript definitions but not used in current implementation */

87

name?: any[] | any[][];

88

/** PostCSS plugins array */

89

plugins?: any[];

90

/** Auto-enable CSS modules for .module.* files (default: true) */

91

autoModules?: boolean;

92

/** Use named exports alongside default export */

93

namedExports?: boolean | ((id: string) => string);

94

/** Minimize CSS with cssnano */

95

minimize?: boolean | any;

96

/** PostCSS parser (e.g., 'sugarss') */

97

parser?: string | FunctionType;

98

/** PostCSS stringifier */

99

stringifier?: string | FunctionType;

100

/** PostCSS syntax */

101

syntax?: string | FunctionType;

102

/** Enable PostCSS Parser support in CSS-in-JS */

103

exec?: boolean;

104

/** PostCSS config file options */

105

config?: boolean | { path: string; ctx: any };

106

/** PostCSS 'to' option hint for plugins */

107

to?: string;

108

/** Custom loaders array (simplified as any[] in TypeScript definitions) */

109

loaders?: any[];

110

/** Callback when CSS file is imported */

111

onImport?: (id: string) => void;

112

/** Preprocessor configuration */

113

use?: string[] | { [key in 'sass' | 'stylus' | 'less']: any };

114

/** Source map generation */

115

sourceMap?: boolean | 'inline';

116

/** Include patterns for rollup-pluginutils filter */

117

include?: Parameters<CreateFilter>[0];

118

/** Exclude patterns for rollup-pluginutils filter */

119

exclude?: Parameters<CreateFilter>[1];

120

}

121

122

type OnExtractAsset = Readonly<{

123

code: any;

124

map: any;

125

codeFileName: string;

126

mapFileName: string;

127

}>;

128

129

// Note: While TypeScript definitions use any[] for loaders,

130

// the actual implementation expects objects with this structure:

131

interface Loader {

132

name: string;

133

test: RegExp;

134

process: (this: LoaderContext, input: Payload) => Promise<Payload> | Payload;

135

}

136

137

interface LoaderContext {

138

/** Loader options */

139

options: any;

140

/** Source map configuration */

141

sourceMap: boolean | 'inline';

142

/** Resource path */

143

id: string;

144

/** Files to watch */

145

dependencies: Set<string>;

146

/** Emit a warning */

147

warn: (warning: any) => void;

148

/** Rollup plugin context */

149

plugin: any;

150

}

151

152

interface Payload {

153

/** File content */

154

code: string;

155

/** Source map */

156

map?: string | any;

157

}

158

```

159

160

**Usage Examples:**

161

162

```javascript

163

// Basic usage with PostCSS plugins

164

import postcss from 'rollup-plugin-postcss';

165

import autoprefixer from 'autoprefixer';

166

167

export default {

168

plugins: [

169

postcss({

170

plugins: [autoprefixer()]

171

})

172

]

173

};

174

175

// CSS extraction

176

import postcss from 'rollup-plugin-postcss';

177

178

export default {

179

plugins: [

180

postcss({

181

extract: true, // Extract to [bundle].css

182

// Or extract to custom file

183

extract: 'dist/styles.css'

184

})

185

]

186

};

187

188

// CSS Modules

189

import postcss from 'rollup-plugin-postcss';

190

191

export default {

192

plugins: [

193

postcss({

194

modules: true,

195

// Or with custom options

196

modules: {

197

generateScopedName: '[name]__[local]___[hash:base64:5]'

198

}

199

})

200

]

201

};

202

```

203

204

### CSS Injection

205

206

Controls how CSS is injected into the document.

207

208

```javascript { .api }

209

// Configuration options for CSS injection

210

inject?: boolean | Record<string, any> | ((cssVariableName: string, id: string) => string);

211

```

212

213

When `inject` is `true` (default), CSS is injected into the document `<head>` using the `style-inject` library. When `extract` is `true`, injection is automatically disabled.

214

215

**Custom injection function:**

216

217

```javascript

218

postcss({

219

inject: (cssVariableName, id) => `

220

import styleInject from 'style-inject';

221

styleInject(${cssVariableName}, { insertAt: 'top' });

222

`

223

});

224

```

225

226

### CSS Extraction

227

228

Extracts CSS to separate files instead of injecting into JavaScript.

229

230

```javascript { .api }

231

// Configuration options for CSS extraction

232

extract?: boolean | string;

233

onExtract?: (asset: ExtractAsset) => boolean;

234

```

235

236

**Usage Examples:**

237

238

```javascript

239

// Extract to default location ([bundle].css)

240

postcss({ extract: true });

241

242

// Extract to custom file

243

postcss({ extract: 'dist/styles.css' });

244

245

// Custom extraction logic

246

postcss({

247

extract: true,

248

onExtract(getExtracted) {

249

const { code, map, codeFileName, mapFileName } = getExtracted();

250

// Custom processing

251

return true; // Continue with extraction

252

}

253

});

254

```

255

256

### CSS Modules

257

258

Enables CSS Modules for locally scoped CSS classes.

259

260

```javascript { .api }

261

// Configuration options for CSS modules

262

modules?: boolean | Record<string, any>;

263

autoModules?: boolean;

264

namedExports?: boolean | ((id: string) => string);

265

```

266

267

**Usage Examples:**

268

269

```javascript

270

// Enable CSS modules

271

postcss({ modules: true });

272

273

// Custom CSS modules configuration

274

postcss({

275

modules: {

276

generateScopedName: '[name]__[local]___[hash:base64:5]',

277

localsConvention: 'camelCase'

278

}

279

});

280

281

// Auto-enable for .module.css files

282

postcss({ autoModules: true });

283

284

// Named exports alongside default

285

postcss({

286

modules: true,

287

namedExports: true

288

});

289

```

290

291

In your JavaScript:

292

293

```javascript

294

// Default export (object with class mappings)

295

import styles from './component.module.css';

296

297

// Named exports (with namedExports: true)

298

import styles, { header, content } from './component.module.css';

299

```

300

301

### Preprocessor Support

302

303

Built-in support for Sass, Stylus, and Less preprocessors. Requires installing the corresponding preprocessor packages:

304

305

```javascript { .api }

306

// Configuration options for preprocessors

307

use?: string[] | { [key in 'sass' | 'stylus' | 'less']: any };

308

```

309

310

**Prerequisites:**

311

- For Sass/SCSS: `npm install sass` or `npm install node-sass`

312

- For Stylus: `npm install stylus`

313

- For Less: `npm install less`

314

315

**Usage Examples:**

316

317

```javascript

318

// Default preprocessor support

319

postcss({

320

use: ['sass', 'stylus', 'less']

321

});

322

323

// Custom preprocessor options

324

postcss({

325

use: {

326

sass: {

327

includePaths: ['node_modules'],

328

data: '$primary-color: #333;'

329

},

330

stylus: {

331

paths: ['src/styles'],

332

import: ['mixins.styl']

333

},

334

less: {

335

paths: ['src/styles'],

336

globalVars: { primaryColor: '#333' }

337

}

338

}

339

});

340

341

// Specific preprocessors only

342

postcss({

343

use: [['sass', { includePaths: ['node_modules'] }]]

344

});

345

```

346

347

### CSS Minimization

348

349

Minimizes CSS output using cssnano.

350

351

```javascript { .api }

352

// Configuration options for CSS minimization

353

minimize?: boolean | any;

354

```

355

356

**Usage Examples:**

357

358

```javascript

359

// Enable minimization

360

postcss({ minimize: true });

361

362

// Custom cssnano options

363

postcss({

364

minimize: {

365

preset: ['default', {

366

discardComments: { removeAll: true }

367

}]

368

}

369

});

370

```

371

372

### PostCSS Configuration

373

374

Controls PostCSS processing options and configuration loading.

375

376

```javascript { .api }

377

// PostCSS configuration options

378

plugins?: any[];

379

parser?: string | Function;

380

stringifier?: string | Function;

381

syntax?: string | Function;

382

exec?: boolean;

383

config?: boolean | { path: string; ctx: any };

384

to?: string;

385

```

386

387

**Usage Examples:**

388

389

```javascript

390

// PostCSS plugins

391

postcss({

392

plugins: [

393

require('autoprefixer'),

394

require('postcss-nested')

395

]

396

});

397

398

// Custom parser (e.g., SugarSS)

399

postcss({

400

parser: 'sugarss',

401

extensions: ['.sss']

402

});

403

404

// PostCSS config file

405

postcss({

406

config: {

407

path: './postcss.config.js',

408

ctx: { env: 'production' }

409

}

410

});

411

412

// CSS-in-JS support

413

postcss({ exec: true });

414

```

415

416

### File Processing

417

418

Controls which files are processed and how.

419

420

```javascript { .api }

421

// File processing configuration

422

extensions?: string[]; // Default: ['.css', '.sss', '.pcss']

423

include?: Parameters<CreateFilter>[0];

424

exclude?: Parameters<CreateFilter>[1];

425

onImport?: (id: string) => void;

426

```

427

428

**Usage Examples:**

429

430

```javascript

431

// Custom extensions (default is ['.css', '.sss', '.pcss'])

432

postcss({

433

extensions: ['.css', '.pcss', '.sss']

434

});

435

436

// Include/exclude patterns

437

postcss({

438

include: ['src/**/*.css'],

439

exclude: ['**/*.module.css']

440

});

441

442

// Import callback

443

postcss({

444

onImport: (id) => {

445

console.log(`Processing CSS file: ${id}`);

446

}

447

});

448

```

449

450

### Source Maps

451

452

Enables source map generation for CSS.

453

454

```javascript { .api }

455

// Source map configuration

456

sourceMap?: boolean | 'inline';

457

```

458

459

**Usage Examples:**

460

461

```javascript

462

// Enable source maps

463

postcss({ sourceMap: true });

464

465

// Inline source maps

466

postcss({ sourceMap: 'inline' });

467

```

468

469

### Custom Loaders

470

471

Extend the plugin with custom file processing loaders.

472

473

```javascript { .api }

474

// Custom loader configuration (TypeScript types show any[], but implementation expects Loader objects)

475

loaders?: any[];

476

477

// Expected structure for custom loaders:

478

interface Loader {

479

name: string;

480

test: RegExp;

481

process: (this: LoaderContext, input: Payload) => Promise<Payload> | Payload;

482

}

483

```

484

485

**Usage Example:**

486

487

```javascript

488

postcss({

489

loaders: [

490

{

491

name: 'my-loader',

492

test: /\.mycss$/,

493

process({ code }) {

494

// Transform the code

495

return { code: transformedCode };

496

}

497

}

498

]

499

});

500

```