
Security News
vlt Launches "reproduce": A New Tool Challenging the Limits of Package Provenance
vlt's new "reproduce" tool verifies npm packages against their source code, outperforming traditional provenance adoption in the JavaScript ecosystem.
postcss-loader
Advanced tools
The postcss-loader npm package is a loader for webpack that allows you to use PostCSS to process CSS with JavaScript. It enables the use of PostCSS plugins to perform various operations on CSS files, such as autoprefixing, minification, and custom transformations.
Autoprefixing
Automatically adds vendor prefixes to CSS rules using values from Can I Use. It is useful for supporting multiple browser versions.
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: [
'style-loader',
'css-loader',
{
loader: 'postcss-loader',
options: {
postcssOptions: {
plugins: [
require('autoprefixer')
]
}
}
}
]
}
]
}
};
CSS Minification
Optimizes and minifies CSS files to reduce file size and improve load times.
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: [
'style-loader',
'css-loader',
{
loader: 'postcss-loader',
options: {
postcssOptions: {
plugins: [
require('cssnano')()
]
}
}
}
]
}
]
}
};
Custom Transformations
Applies custom transformations or future CSS features using PostCSS plugins.
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: [
'style-loader',
'css-loader',
{
loader: 'postcss-loader',
options: {
postcssOptions: {
plugins: [
require('postcss-custom-properties')()
]
}
}
}
]
}
]
}
};
The sass-loader compiles Sass/SCSS files to CSS. It requires Node.js-style .sass/.scss files. Unlike postcss-loader, it's specifically designed for Sass pre-processing.
The less-loader processes .less files and compiles them to CSS. It's similar to postcss-loader in that it transforms styles, but it's tailored for the Less pre-processor.
This package is a webpack loader that compiles Stylus files to CSS. It's a pre-processor loader like sass-loader and less-loader, but for Stylus syntax.
Loader to process CSS with PostCSS
.
To begin, you'll need to install postcss-loader
and postcss
:
npm install --save-dev postcss-loader postcss
Then add the plugin to your webpack
config. For example:
file.js
import css from 'file.css';
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
use: [
'style-loader',
'css-loader',
{
loader: 'postcss-loader',
options: {
postcssOptions: {
plugins: [
'postcss-present-env',
{
// Options
},
],
},
},
},
],
},
],
},
};
Alternative use with config files:
postcss.config.js
module.exports = {
plugins: [
[
'postcss-preset-env',
{
// Options
},
],
],
};
The loader automatically searches for configuration files.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
use: ['style-loader', 'css-loader', 'postcss-loader'],
},
],
},
};
And run webpack
via your preferred method.
Name | Type | Default | Description |
---|---|---|---|
execute | {Boolean} | undefined | Enable PostCSS Parser support in CSS-in-JS |
postcssOptions | {Object\/Function} | defaults values for Postcss.process | Set PostCSS options and plugins |
sourceMap | {Boolean} | compiler.devtool | Enables/Disables generation of source maps |
execute
Type: Boolean
Default: undefined
If you use JS styles the postcss-js
parser, add the execute
option.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.style.js$/,
use: [
'style-loader',
{
loader: 'css-loader',
},
{
loader: 'postcss-loader',
options: {
postcssOptions: {
parser: 'postcss-js',
},
execute: true,
},
},
],
},
],
},
};
postcssOptions
Type: Object|Function
Default: undefined
Allows to set PostCSS options
and plugins.
All PostCSS
options are supported.
There is the special config
option for config files. How it works and how it can be configured is described below.
We recommend do not specify from
, to
and map
options, because this can lead to wrong path in source maps.
If you need source maps please use the sourcemap
option.
Object
Setup plugins
:
webpack.config.js (recommended)
const myOtherPostcssPlugin = require('postcss-my-plugin');
module.exports = {
module: {
rules: [
{
test: /\.sss$/i,
loader: 'postcss-loader',
options: {
postcssOptions: {
plugins: [
'postcss-import',
['postcss-short', { prefix: 'x' }],
require.resolve('my-postcss-plugin'),
myOtherPostcssPlugin({ myOption: true }),
// Deprecated and will be removed in the next major release
{ 'postcss-nested': { preserveEmpty: true } },
],
},
},
},
],
},
};
webpack.config.js (deprecated, will be removed in the next major release)
module.exports = {
module: {
rules: [
{
test: /\.sss$/i,
loader: 'postcss-loader',
options: {
postcssOptions: {
plugins: {
'postcss-import': {},
'postcss-short': { prefix: 'x' },
},
},
},
},
],
},
};
Setup syntax
:
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.sss$/i,
loader: 'postcss-loader',
options: {
postcssOptions: {
// Can be `String`
syntax: 'sugarss',
// Can be `Object`
syntax: require('sugarss'),
},
},
},
],
},
};
Setup parser
:
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.sss$/i,
loader: 'postcss-loader',
options: {
postcssOptions: {
// Can be `String`
parser: 'sugarss',
// Can be `Object`
parser: require('sugarss'),
// Can be `Function`
parser: require('sugarss').parse,
},
},
},
],
},
};
Setup stringifier
:
webpack.config.js
const Midas = require('midas');
const midas = new Midas();
module.exports = {
module: {
rules: [
{
test: /\.sss$/i,
loader: 'postcss-loader',
options: {
postcssOptions: {
// Can be `String`
stringifier: 'sugarss',
// Can be `Object`
stringifier: require('sugarss'),
// Can be `Function`
stringifier: midas.stringifier,
},
},
},
],
},
};
Function
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.(css|sss)$/i,
loader: 'postcss-loader',
options: {
postcssOptions: (loaderContext) => {
if (/\.sss$/.test(loaderContext.resourcePath)) {
return {
parser: 'sugarss',
plugins: [
['postcss-short', { prefix: 'x' }],
'postcss-present-env',
],
};
}
return {
plugins: [
['postcss-short', { prefix: 'x' }],
'postcss-present-env',
],
};
},
},
},
],
},
};
config
Type: Boolean|String
Default: undefined
Allows to set options using config files. Options specified in the config file are combined with options passed to the loader, the loader options overwrite options from config.
The loader will search up the directory tree for configuration in the following places:
postcss
property in package.json
.postcssrc
file in JSON or YAML format.postcss.json
, .postcss.yaml
, .postcss.yml
, .postcss.js
, or .postcss.cjs
filepostcss.config.js
or postcss.config.cjs
CommonJS module exporting an object (recommended)Using Object
notation:
postcss.config.js (recommend)
module.exports = {
// You can specify any options from http://api.postcss.org/global.html#processOptions here
// parser: 'sugarss',
plugins: [
// Plugins for PostCSS
['postcss-short', { prefix: 'x' }],
'postcss-present-env',
],
};
Using Function
notation:
postcss.config.js (recommend)
module.exports = (api) => {
// `api.file` - path to the file
// `api.mode` - `mode` value of webpack, please read https://webpack.js.org/configuration/mode/
// `api.webpackLoaderContext` - loader context for complex use cases
if (/\.sss$/.test(api.file)) {
return {
// You can specify any options from http://api.postcss.org/global.html#processOptions here
parser: 'sugarss',
plugins: [
// Plugins for PostCSS
['postcss-short', { prefix: 'x' }],
'postcss-present-env',
],
};
}
return {
// You can specify any options from http://api.postcss.org/global.html#processOptions here
plugins: [
// Plugins for PostCSS
['postcss-short', { prefix: 'x' }],
'postcss-present-env',
],
};
};
postcss.config.js (deprecated, will be removed in the next major release)
module.exports = {
// You can specify any options from http://api.postcss.org/global.html#processOptions here
// parser: 'sugarss',
plugins: {
// Plugins for PostCSS
'postcss-short': { prefix: 'x' },
'postcss-present-env': {},
},
};
You can use different postcss.config.js
files in different directories.
Config lookup starts from path.dirname(file)
and walks the file tree upwards until a config file is found.
|– components
| |– component
| | |– index.js
| | |– index.png
| | |– style.css (1)
| | |– postcss.config.js (1)
| |– component
| | |– index.js
| | |– image.png
| | |– style.css (2)
|
|– postcss.config.js (1 && 2 (recommended))
|– webpack.config.js
|
|– package.json
After setting up your postcss.config.js
, add postcss-loader
to your webpack.config.js
.
You can use it standalone or in conjunction with css-loader
(recommended).
Use it before css-loader
and style-loader
, but after other preprocessor loaders like e.g sass|less|stylus-loader
, if you use any (since webpack loaders evaluate right to left/bottom to top).
webpack.config.js (recommended)
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
importLoaders: 1,
},
},
'postcss-loader',
],
},
],
},
};
Enables/Disables autoloading config.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
loader: 'postcss-loader',
options: {
config: false,
},
},
],
},
};
Allows to specify the path to the config file.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
loader: 'postcss-loader',
options: {
config: path.resolve(__dirname, 'custom.config.js'),
},
},
],
},
};
sourceMap
Type: Boolean
Default: depends on the compiler.devtool
value
By default generation of source maps depends on the devtool
option.
All values enable source map generation except eval
and false
value.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
use: [
{ loader: 'style-loader' },
{ loader: 'css-loader', options: { sourceMap: true } },
{ loader: 'postcss-loader', options: { sourceMap: true } },
{ loader: 'sass-loader', options: { sourceMap: true } },
],
},
],
},
};
Alternative setup:
webpack.config.js
module.exports = {
devtool: 'source-map',
module: {
rules: [
{
test: /\.css$/i,
use: [
{ loader: 'style-loader' },
{ loader: 'css-loader' },
{ loader: 'postcss-loader' },
{ loader: 'sass-loader' },
],
},
],
},
};
You'll need to install sugarss
:
npm install --save-dev sugarss
Using SugarSS
syntax.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.sss$/i,
use: [
'style-loader',
{
loader: 'css-loader',
options: { importLoaders: 1 },
},
{
loader: 'postcss-loader',
options: {
postcssOptions: {
parser: 'sugarss',
},
},
},
],
},
],
},
};
You'll need to install autoprefixer
:
npm install --save-dev autoprefixer
Add vendor prefixes to CSS rules using autoprefixer
.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
use: [
'style-loader',
{
loader: 'css-loader',
options: { importLoaders: 1 },
},
{
loader: 'postcss-loader',
options: {
postcssOptions: {
plugins: [
[
'autoprefixer',
{
// Options
},
],
],
},
},
},
],
},
],
},
};
:warning:
postcss-preset-env
includesautoprefixer
, so adding it separately is not necessary if you already use the preset. More information
You'll need to install postcss-preset-env
:
npm install --save-dev postcss-preset-env
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
use: [
'style-loader',
{
loader: 'css-loader',
options: { importLoaders: 1 },
},
{
loader: 'postcss-loader',
options: {
postcssOptions: {
plugins: [
[
'postcss-preset-env',
{
// Options
},
],
],
},
},
},
],
},
],
},
};
What is CSS Modules
? Please read.
No additional options required on the postcss-loader
side.
To make them work properly, either add the css-loader
’s importLoaders
option.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
modules: true,
importLoaders: 1,
},
},
'postcss-loader',
],
},
],
},
};
postcss-js
You'll need to install postcss-js
:
npm install --save-dev postcss-js
If you want to process styles written in JavaScript, use the postcss-js
parser.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.style.js$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
importLoaders: 2,
},
},
{
loader: 'postcss-loader',
options: {
postcssOptions: {
parser: 'postcss-js',
},
execute: true,
},
},
'babel-loader',
],
},
],
},
};
As result you will be able to write styles in the following way
import colors from './styles/colors';
export default {
'.menu': {
color: colors.main,
height: 25,
'&_link': {
color: 'white',
},
},
};
:warning: If you are using Babel you need to do the following in order for the setup to work
- Add
babel-plugin-add-module-exports
to your configuration.- You need to have only one default export per style module.
Using mini-css-extract-plugin
.
webpack.config.js
const isProductionMode = process.env.NODE_ENV === 'production';
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
mode: isProductionMode ? 'production' : 'development',
module: {
rules: [
{
test: /\.css$/,
use: [
isProductionMode ? MiniCssExtractPlugin.loader : 'style-loader',
'css-loader',
'postcss-loader',
],
},
],
},
plugins: [
new MiniCssExtractPlugin({
filename: isProductionMode ? '[name].[contenthash].css' : '[name].css',
}),
],
};
To write a asset from PostCSS plugin to the webpack, need to add a message in result.messages
.
The message should contain the following fields:
type
= asset
- Message type (require, should be equal asset
)file
- file name (require)content
- file content (require)sourceMap
- sourceMapinfo
- asset infowebpack.config.js
const customPlugin = () => (css, result) => {
result.messages.push({
type: 'asset',
file: 'sprite.svg',
content: '<svg>...</svg>',
});
};
const postcssPlugin = postcss.plugin('postcss-assets', customPlugin);
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
use: [
'style-loader',
'css-loader',
{
loader: 'postcss-loader',
options: {
postcssOptions: {
plugins: [postcssPlugin()],
},
},
},
],
},
],
},
};
The dependencies are necessary for webpack to understand when it needs to run recompilation on the changed files.
There are two way to add dependencies:
result.messages
.The message should contain the following fields:
type
= dependency
- Message type (require, should be equal dependency
)file
- absolute file path (require)webpack.config.js
const path = require('path');
const customPlugin = () => (css, result) => {
result.messages.push({
type: 'dependency',
file: path.resolve(__dirname, 'path', 'to', 'file'),
});
};
const postcssPlugin = postcss.plugin('postcss-assets', customPlugin);
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
use: [
'style-loader',
'css-loader',
{
loader: 'postcss-loader',
options: {
postcssOptions: {
plugins: [postcssPlugin()],
},
},
},
],
},
],
},
};
loaderContext
in plugin.webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
use: [
'style-loader',
'css-loader',
{
loader: 'postcss-loader',
options: {
config: 'path/to/postcss.config.js',
},
},
],
},
],
},
};
postcss.config.js
module.exports = (api) => ({
plugins: [
require('path/to/customPlugin')({
loaderContext: api.webpackLoaderContext,
}),
],
});
customPlugin.js
const path = require('path');
const customPlugin = (loaderContext) => (css, result) => {
loaderContext.webpack.addDependency(
path.resolve(__dirname, 'path', 'to', 'file')
);
};
module.exports = postcss.plugin('postcss-assets', customPlugin);
Please take a moment to read our contributing guidelines if you haven't yet done so.
4.0.0 (2020-09-07)
Node.js
version is 10.13
webpack
version is 4
postcss
was moved to peerDependencies
, you need to install postcss
PostCSS
(plugins
/syntax
/parser
/stringifier
) options was moved to the postcssOptions
option, please look at docssourceMap
default value depends on the compiler.devtool
optioninline
value was removed for the sourceMap
option, please use { map: { inline: true, annotation: false } }
to achieve thissources
css-loader
/file-loader
/raw-loader
to inject code inside bundleexec
option was renamed to the execute
optionconfig
option doesn't support Object
type anymore, config.path
and config.ctx
options were removedFunction
notation (previously config.ctx
) was changed, now it contains { file, mode, webpackLoaderContext }
webpack
to webpackLoaderContext
plugins
option from the config and options are merged (0eb5aaf)postcssOptions
options can be Function
default
export for plugins (#465) (3d32c35)map
option from loader options and config (#458) (98441ff)ident
option for loaderObject
syntax for the plugin
option is soft deprecated, please migrate on Array
syntax (plugins: ['postcss-preset-env', ['cssnano', options]]
)<a name="3.0.0"></a>
FAQs
PostCSS loader for webpack
The npm package postcss-loader receives a total of 13,650,060 weekly downloads. As such, postcss-loader popularity was classified as popular.
We found that postcss-loader demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 4 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
vlt's new "reproduce" tool verifies npm packages against their source code, outperforming traditional provenance adoption in the JavaScript ecosystem.
Research
Security News
Socket researchers uncovered a malicious PyPI package exploiting Deezer’s API to enable coordinated music piracy through API abuse and C2 server control.
Research
The Socket Research Team discovered a malicious npm package, '@ton-wallet/create', stealing cryptocurrency wallet keys from developers and users in the TON ecosystem.