- webpack概述
- 入口起点(Entry Points)
- 输出(Output)
- 模块(Mode)
- 加载器(Loaders)
- 插件(Plugins)
- 配置(Configuration)
- 模块(Modules)
- 模块解析(Module Resolution)
- 依赖图表(Dependency Graph)
- 文件清单(Manifest)
- 构建目标(Targets)
- 模块热替换(Hot Module Replacement)
- 第二部分:配置
- 使用不同语言进行配置(Configuration Languages)
- 多种配置类型
- 入口和上下文(Entry and Context)
- 输出(Output)
- 模块(Module)
- 解析(Resolve)
- 插件(Plugins)
- 开发中 Server(DevServer)
- 开发工具(Devtool)
- 构建目标(Targets)
- Watch 和 WatchOptions
- 外部扩展(Externals)
- 性能(Performance)
- Node
- 统计(Stats)
- 其它选项(Other Options)
- 第三部分:API
- 命令行接口(CLI)
- 包含统计数据的文件(stats data)
- Node.js API
- 模块热替换(Hot Module Replacement)
- 加载器 API
- 模块方法(module methods)
- 模块变量(module variables)
- Plugin API
- compiler 钩子
- compilation 钩子
- resolver
- parser
- 第四部分:指南
- 安装
- 起步
- 管理资源
- 管理输出
- 开发
- 模块热替换
- Tree shaking
- 生产环境构建
- 代码拆分(Code Splitting)
- 懒加载(Lazy Loading)
- 缓存(Caching)
- 创建库 (Library)
- Shimming
- 渐进式网络应用程序
- TypeScript
- 迁移到新版本
- 使用环境变量
- 构建性能
- 内容安全策略
- 开发 - Vagrant
- 管理依赖
- Public Path(公共路径)
- 集成(Integrations)
- 第五部分:加载器
- babel-loader
- yaml-frontmatter-loader
- cache-loader
- coffee-loader
- coffee-redux-loader
- coverjs-loader
- css-loader
- exports-loader
- expose-loader
- extract-loader
- file-loader
- gzip-loader
- html-loader
- i18n-loader
- imports-loader
- istanbul-instrumenter-loader
- jshint-loader
- json-loader
- json5-loader
- less-loader
- bundle-loader
- multi-loader
- node-loader
- null-loader
- polymer-webpack-loader
- postcss-loader
- raw-loader
- react-proxy-loader
- restyle-loader
- sass-loader
- script-loader
- source-map-loader
- style-loader
- svg-inline-loader
- thread-loader
- transform-loader
- url-loader
- val-loader
- worker-loader
- mocha-loader
- 第六部分:插件
- AggressiveSplittingPlugin
- ZopfliWebpackPlugin
- BannerPlugin
- ClosureWebpackPlugin
- CommonsChunkPlugin
- ComponentWebpackPlugin
- CompressionWebpackPlugin
- ContextReplacementPlugin
- CopyWebpackPlugin
- DefinePlugin
- DllPlugin
- EnvironmentPlugin
- EvalSourceMapDevToolPlugin
- ExtractTextWebpackPlugin
- HashedModuleIdsPlugin
- HotModuleReplacementPlugin
- HtmlWebpackPlugin
- BabelMinifyWebpackPlugin
- IgnorePlugin
- LoaderOptionsPlugin
- MinChunkSizePlugin
- ModuleConcatenationPlugin
- NamedModulesPlugin
- NormalModuleReplacementPlugin
- NpmInstallWebpackPlugin
- PrefetchPlugin
- ProfilingPlugin
- ProvidePlugin
- SourceMapDevToolPlugin
- SplitChunksPlugin
- UglifyjsWebpackPlugin
- WatchIgnorePlugin
- I18nWebpackPlugin
postcss-loader
Loader for webpack to process CSS with PostCSS
</div>Install
npm i -D postcss-loader
Usage
postcss.config.js
module.exports = {
parser: 'sugarss',
plugins: {
'postcss-import': {},
'postcss-cssnext': {},
'cssnano': {}
}
}
You can read more about common PostCSS Config here.
Config Cascade
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 after css-loader
and style-loader
, but before other preprocessor loaders like e.g sass|less|stylus-loader
, if you use any.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: [ 'style-loader', 'postcss-loader' ]
}
]
}
}
⚠️ When
postcss-loader
is used standalone (withoutcss-loader
) don't use@import
in your CSS, since this can lead to quite bloated bundles
webpack.config.js (recommended)
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: [
'style-loader',
{ loader: 'css-loader', options: { importLoaders: 1 } },
'postcss-loader'
]
}
]
}
}
Options
Name | Type | Default | Description | |
---|---|---|---|---|
exec | {Boolean} | undefined | Enable PostCSS Parser support in CSS-in-JS | |
parser | `{String\ | Object}` | undefined | Set PostCSS Parser |
syntax | `{String\ | Object}` | undefined | Set PostCSS Syntax |
stringifier | `{String\ | Object}` | undefined | Set PostCSS Stringifier |
config | {Object} | undefined | Set postcss.config.js config path && ctx | |
plugins | `{Array\ | Function}` | [] | Set PostCSS Plugins |
sourceMap | `{String\ | Boolean}` | false | Enable Source Maps |
Exec
If you use JS styles without the postcss-js
parser, add the exec
option.
{
test: /\.style.js$/,
use: [
'style-loader',
{ loader: 'css-loader', options: { importLoaders: 1 } },
{ loader: 'postcss-loader', options: { parser: 'sugarss', exec: true } }
]
}
Config
Name | Type | Default | Description |
---|---|---|---|
path | {String} | undefined | PostCSS Config Path |
context | {Object} | undefined | PostCSS Config Context |
Path
You can manually specify the path to search for your config (postcss.config.js
) with the config.path
option. This is needed if you store your config in a separate e.g ./config || ./.config
folder.
⚠️ Otherwise it is unnecessary to set this option and is not recommended
webpack.config.js
{
loader: 'postcss-loader',
options: {
config: {
path: 'path/to/postcss.config.js'
}
}
}
Context (ctx)
Name | Type | Default | Description |
---|---|---|---|
env | {String} | 'development' | process.env.NODE_ENV |
file | {Object} | loader.resourcePath | extname , dirname , basename |
options | {Object} | {} | Options |
postcss-loader
exposes context ctx
to the config file, making your postcss.config.js
dynamic, so can use it to do some real magic ✨
postcss.config.js
module.exports = ({ file, options, env }) => ({
parser: file.extname === '.sss' ? 'sugarss' : false,
plugins: {
'postcss-import': { root: file.dirname },
'postcss-cssnext': options.cssnext ? options.cssnext : false,
'autoprefixer': env == 'production' ? options.autoprefixer : false,
'cssnano': env === 'production' ? options.cssnano : false
}
})
webpack.config.js
{
loader: 'postcss-loader',
options: {
config: {
ctx: {
cssnext: {...options},
cssnano: {...options},
autoprefixer: {...options}
}
}
}
}
Plugins
webpack.config.js
{
loader: 'postcss-loader',
options: {
ident: 'postcss',
plugins: (loader) => [
require('postcss-import')({ root: loader.resourcePath }),
require('postcss-cssnext')(),
require('autoprefixer')(),
require('cssnano')()
]
}
}
⚠️ webpack requires an identifier (
ident
) inoptions
when{Function}/require
is used (Complex Options). Theident
can be freely named as long as it is unique. It's recommended to name it (ident: 'postcss'
)
Syntaxes
Name | Type | Default | Description | |
---|---|---|---|---|
parser | `{String\ | Function}` | undefined | Custom PostCSS Parser |
syntax | `{String\ | Function}` | undefined | Custom PostCSS Syntax |
stringifier | `{String\ | Function}` | undefined | Custom PostCSS Stringifier |
Parser
webpack.config.js
{
test: /\.sss$/,
use: [
...,
{ loader: 'postcss-loader', options: { parser: 'sugarss' } }
]
}
Syntax
webpack.config.js
{
test: /\.css$/,
use: [
...,
{ loader: 'postcss-loader', options: { syntax: 'sugarss' } }
]
}
Stringifier
webpack.config.js
{
test: /\.css$/,
use: [
...,
{ loader: 'postcss-loader', options: { stringifier: 'midas' } }
]
}
SourceMap
Enables source map support, postcss-loader
will use the previous source map given by other loaders and update it accordingly, if no previous loader is applied before postcss-loader
, the loader will generate a source map for you.
:warning: If a previous loader like e.g
sass-loader
is applied and it'ssourceMap
option is set, but thesourceMap
option inpostcss-loader
is omitted, previous source maps will be discarded bypostcss-loader
entirely.
webpack.config.js
{
test: /\.css/,
use: [
{ loader: 'style-loader', options: { sourceMap: true } },
{ loader: 'css-loader', options: { sourceMap: true } },
{ loader: 'postcss-loader', options: { sourceMap: true } },
{ loader: 'sass-loader', options: { sourceMap: true } }
]
}
'inline'
You can set the sourceMap: 'inline'
option to inline the source map within the CSS directly as an annotation comment.
webpack.config.js
{
loader: 'postcss-loader',
options: {
sourceMap: 'inline'
}
}
.class { color: red; }
/*# sourceMappingURL=data:application/json;base64, ... */
Examples
Stylelint
webpack.config.js
{
test: /\.css$/,
use: [
'style-loader',
'css-loader',
{
loader: 'postcss-loader',
options: {
ident: 'postcss',
plugins: [
require('postcss-import')(),
require('stylelint')(),
...,
]
}
}
]
}
CSS Modules
This loader cannot be used with CSS Modules out of the box due to the way css-loader
processes file imports. To make them work properly, either add the css-loader’s importLoaders
option.
webpack.config.js
{
test: /\.css$/,
use: [
'style-loader',
{ loader: 'css-loader', options: { modules: true, importLoaders: 1 } },
'postcss-loader'
]
}
or use postcss-modules instead of css-loader
.
CSS-in-JS
If you want to process styles written in JavaScript, use the postcss-js parser.
{
test: /\.style.js$/,
use: [
'style-loader',
{ loader: 'css-loader', options: { importLoaders: 2 } },
{ loader: 'postcss-loader', options: { parser: 'postcss-js' } },
'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
Extract CSS
webpack.config.js
const ExtractTextPlugin = require('extract-text-webpack-plugin')
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
{ loader: 'css-loader', options: { importLoaders: 1 } },
'postcss-loader'
]
})
}
]
},
plugins: [
new ExtractTextPlugin('[name].css')
]
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论