Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork211
webpack-contrib/postcss-loader
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
A loader to process CSS usingPostCSS
.
You need webpack v5 to use the latest version. For Webpack v4, you have to install postcss-loader v4.
To begin, you'll need to installpostcss-loader
andpostcss
:
npm install --save-dev postcss-loader postcss
or
yarn add -D postcss-loader postcss
or
pnpm add -D postcss-loader postcss
Then add the loader to yourwebpack
configuration. For example:
In the following configuration the plugin
postcss-preset-env
is used, which is not installed by default.
file.js
importcssfrom"file.css";
webpack.config.js
module.exports={module:{rules:[{test:/\.css$/i,use:["style-loader","css-loader",{loader:"postcss-loader",options:{postcssOptions:{plugins:[["postcss-preset-env",{// Options},],],},},},],},],},};
Alternative use withconfig files:
postcss.config.js
module.exports={plugins:[["postcss-preset-env",{// Options},],],};
The loaderautomatically searches for configuration files.
webpack.config.js
module.exports={module:{rules:[{test:/\.css$/i,use:["style-loader","css-loader","postcss-loader"],},],},};
Finally, runwebpack
using the method you normally use (e.g., via CLI or an npm script).
Type:
typeexecute=boolean;
Default:undefined
Enable PostCSS parser support forCSS-in-JS
.If you use JS styles thepostcss-js
parser, add theexecute
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,},},],},],},};
See the file./src/config.d.ts
.
Type:
importtype{ConfigasPostCSSConfig}from"postcss-load-config";importtype{LoaderContext}from"webpack";typePostCSSLoaderContext=LoaderContext<PostCSSConfig>;interfacePostCSSLoaderAPI{mode:PostCSSLoaderContext["mode"];file:PostCSSLoaderContext["resourcePath"];webpackLoaderContext:PostCSSLoaderContext;env:PostCSSLoaderContext["mode"];options:PostCSSConfig;}exporttypePostCSSLoaderOptions=|PostCSSConfig|((api:PostCSSLoaderAPI)=>PostCSSConfig);
Default:undefined
Allows you to setPostCSS options
and plugins.
AllPostCSS
options are supported.There is the specialconfig
option for config files. How it works and how it can be configured is described below.
We recommend do not specifyfrom
,to
andmap
options, because this can lead to wrong path in source maps.If you need source maps please use thesourcemap
option instead.
For large projects, to optimize performance of the loader, it is better to providepostcssOptions
in loader config and specifyconfig: false
.This approach removes the need to lookup and load external config files multiple times during compilation.
Setupplugins
:
webpack.config.js (recommended)
constmyOtherPostcssPlugin=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"},},},},},],},};
Setupsyntax
:
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"),},},},],},};
Setupparser
:
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,},},},],},};
Setupstringifier
:
webpack.config.js
constMidas=require("midas");constmidas=newMidas();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,},},},],},};
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-preset-env",],};}return{plugins:[["postcss-short",{prefix:"x"}],"postcss-preset-env",],};},},},],},};
Type:
typeconfig=boolean|string;
Default:true
Allows you 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:
- A
postcss
property inpackage.json
- A
.postcssrc
file in JSON or YAML format - A
.postcssrc.json
,.postcssrc.yaml
,.postcssrc.yml
,.postcssrc.js
, or.postcssrc.cjs
file - A
postcss.config.js
orpostcss.config.cjs
CommonJS module exporting an object (recommended)
Usingobject
notation:
postcss.config.js (recommend)
module.exports={// You can specify any options from https://postcss.org/api/#processoptions here// parser: 'sugarss',plugins:[// Plugins for PostCSS["postcss-short",{prefix:"x"}],"postcss-preset-env",],};
Usingfunction
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// `api.env` - alias `api.mode` for compatibility with `postcss-cli`// `api.options` - the `postcssOptions` optionsif(/\.sss$/.test(api.file)){return{// You can specify any options from https://postcss.org/api/#processoptions hereparser:"sugarss",plugins:[// Plugins for PostCSS["postcss-short",{prefix:"x"}],"postcss-preset-env",],};}return{// You can specify any options from https://postcss.org/api/#processoptions hereplugins:[// Plugins for PostCSS["postcss-short",{prefix:"x"}],"postcss-preset-env",],};};
postcss.config.js (deprecated, will be removed in the next major release)
module.exports={// You can specify any options from https://postcss.org/api/#processoptions here// parser: 'sugarss',plugins:{// Plugins for PostCSS"postcss-short":{prefix:"x"},"postcss-preset-env":{},},};
You can use differentpostcss.config.js
files in different directories.Config lookup starts frompath.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 yourpostcss.config.js
, addpostcss-loader
to yourwebpack.config.js
.You can use it standalone or in conjunction withcss-loader
(recommended).
Usepostcss-loader
beforecss-loader
andstyle-loader
, butafter other preprocessor loaders like e.gsass|less|stylus-loader
, if you use any (sincewebpack 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:{postcssOptions:{config:false,},},},],},};
Allows to specify the path to the config file.
webpack.config.js
constpath=require("path");module.exports={module:{rules:[{test:/\.css$/i,loader:"postcss-loader",options:{postcssOptions:{config:path.resolve(__dirname,"custom.config.js"),},},},],},};
Type:
typesourceMap=boolean;
Default: depends on thecompiler.devtool
value
By default generation of source maps depends on thedevtool
option.All values enable source map generation excepteval
andfalse
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"},],},],},};
Type:
typeimplementation=object;
type ofimplementation
should be the same aspostcss.d.ts
Default:postcss
The specialimplementation
option determines which implementation of PostCSS to use. Overrides the locally installedpeerDependency
version ofpostcss
.
This option is only really useful for downstream tooling authors to ease the PostCSS 7-to-8 transition.
webpack.config.js
module.exports={module:{rules:[{test:/\.css$/i,use:[{loader:"style-loader"},{loader:"css-loader"},{loader:"postcss-loader",options:{implementation:require("postcss")},},{loader:"sass-loader"},],},],},};
webpack.config.js
module.exports={module:{rules:[{test:/\.css$/i,use:[{loader:"style-loader"},{loader:"css-loader"},{loader:"postcss-loader",options:{implementation:require.resolve("postcss")},},{loader:"sass-loader"},],},],},};
SugarSS
is a whitespace-based syntax for PostCSS.
You'll need to installsugarss
:
npm install --save-dev sugarss
UsingSugarSS
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 installautoprefixer
:
npm install --save-dev autoprefixer
Automatically add vendor prefixes to CSS rules usingautoprefixer
.
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",{// Autoprefixer options (optional)},],],},},},],},],},};
Warning
postcss-preset-env
includesautoprefixer
, so adding it separately is not necessary if you already use the preset. Moreinformation
You'll need to installpostcss-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 are
CSS Modules
? Pleaseread here.
No additional options required on thepostcss-loader
side to support CSS Modules.To make them work properly, either add thecss-loader
’simportLoaders
option.
webpack.config.js
module.exports={module:{rules:[{test:/\.css$/i,use:["style-loader",{loader:"css-loader",options:{modules:true,importLoaders:1,},},"postcss-loader",],},],},};
CSS-in-JS andpostcss-js
To process styles written in JavaScript, you can usepostcss-js
as the parser.
You'll need to installpostcss-js
:
npm install --save-dev postcss-js
If you want to process styles written in JavaScript, use thepostcss-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:
importcolorsfrom"./styles/colors";exportdefault{".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 onedefault export per style module.
To extract CSS into separate files, usemini-css-extract-plugin
.
webpack.config.js
constisProductionMode=process.env.NODE_ENV==="production";constMiniCssExtractPlugin=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:[newMiniCssExtractPlugin({filename:isProductionMode ?"[name].[contenthash].css" :"[name].css",}),],};
💡 Use this setup to extract and cache CSS in production while keeping fast style injection during development.
To emit an asset from PostCSS plugin to the webpack, need to add a message inresult.messages
.
The message should contain the following fields:
type
=asset
- Message type (require, should be equalasset
)file
- file name (require)content
- file content (require)sourceMap
- sourceMapinfo
- asset info
webpack.config.js
constpostcssCustomPlugin=(opts={})=>{return{postcssPlugin:"postcss-custom-plugin",Once:(root,{ result})=>{result.messages.push({type:"asset",file:"sprite.svg",content:"<svg>...</svg>",});},};};module.exports={module:{rules:[{test:/\.css$/i,use:["style-loader","css-loader",{loader:"postcss-loader",options:{postcssOptions:{plugins:[postcssCustomPlugin()],},},},],},],},};
ℹ️ This allows your plugin to generate additional files as part of the build process, and Webpack will handle them like any other emitted asset.
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:
- (Recommended). The plugin may emit messages in
result.messages
.
The message should contain the following fields:
type
=dependency
- Message type (require, should be equaldependency
,context-dependency
,build-dependency
ormissing-dependency
)file
- absolute file path (require)
webpack.config.js
constpath=require("path");constpostcssCustomPlugin=(opts={})=>{return{postcssPlugin:"postcss-custom-plugin",Once:(root,{ result})=>{result.messages.push({type:"dependency",file:path.resolve(__dirname,"path","to","file"),});},};};module.exports={module:{rules:[{test:/\.css$/i,use:["style-loader","css-loader",{loader:"postcss-loader",options:{postcssOptions:{plugins:[postcssCustomPlugin()],},},},],},],},};
💡 You can use ready-made pluginpostcss-add-dependencies to simplify this process.
- Pass
loaderContext
in plugin (for advanced setups).
webpack.config.js
constpath=require("path");module.exports={module:{rules:[{test:/\.css$/i,use:["style-loader","css-loader",{loader:"postcss-loader",options:{postcssOptions:{config:path.resolve(__dirname,"path/to/postcss.config.js"),},},},],},],},};
⚠️ Use this approach only when managing dependencies via custom PostCSS configurations with dynamic imports or external files.
postcss.config.js
Pass thewebpackLoaderContext
through the PostCSSapi
object:
module.exports=(api)=>({plugins:[require("path/to/postcssCustomPlugin.js")({loaderContext:api.webpackLoaderContext,}),],});
postcssCustomPlugin.js
Register a file dependency usingloaderContext.addDependency
:
constpath=require("path");constpostcssCustomPlugin=(opts={})=>{return{postcssPlugin:"postcss-custom-plugin",Once:(root,{ result})=>{opts.loaderContext.addDependency(path.resolve(__dirname,"path","to","file"),);},};};postcssCustomPlugin.postcss=true;module.exports=postcssCustomPlugin;
✅ This method is ideal when you want to dynamically declare dependencies without relying on result.messages, especially in more complex setups or shared plugin configurations.
We welcome all contributions!If you're new here, please take a moment to review our contributing guidelines before submitting issues or pull requests.
About
PostCSS loader for webpack
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Sponsor this project
Uh oh!
There was an error while loading.Please reload this page.