npm node deps tests coverage chat

PostCSS Logo

1. PostCSS Loader

webpack loader,使用 PostCSS 来处理CSS

postCss

1.1. 安装

npm i -D postcss-loader

1.2. 用法

1.2.1. 配置

postcss.config.js

module.exports = {
  parser: 'sugarss',
  plugins: {
    'postcss-import': {},
    'postcss-cssnext': {},
    'cssnano': {}
  }
}

你可以在这里查看更多关于常见的 PostCSS 配置.

1.2.2. 配置级联(config Cascade)

你可以在不同的目录使用不同的 postcss.config.js 文件 。 配置查找从path.dirname(file)开始,并沿文件树向上走,直到找到一个配置文件。

|– 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

设置好postcss.config.js之后,在webpack.config.js中添加postcss-loader。您可以独立使用它,也可以与css-loader(推荐)结合使用。在css-loaderstyle-loader之后,但是在像如sass|less|stylus-loader这样的预处理器之前使用它。

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [ 'style-loader', 'postcss-loader' ]
      }
    ]
  }
}

[warning] 警告

postcss-loader 被独立使用时(没有css-loader),不要在CSS中使用@import,因为这样会导致导致相当臃肿的bundle

webpack.config.js (推荐)

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          'style-loader',
          { loader: 'css-loader', options: { importLoaders: 1 } },
          'postcss-loader'
        ]
      }
    ]
  }
}

1.3. 选项

名称 类型 默认值 描述
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

1.3.1. 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 } }
  ]
}

1.3.2. 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}
      }
    }
  }
}

1.3.3. 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) in options when {Function}/require is used (Complex Options). The ident can be freely named as long as it is unique. It's recommended to name it (ident: 'postcss')

1.3.4. 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' } }
  ]
}

1.3.5. 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's sourceMap option is set, but the sourceMap option in postcss-loader is omitted, previous source maps will be discarded by postcss-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, ... */

1.4. Examples

1.4.1. Stylelint

webpack.config.js

{
  test: /\.css$/,
  use: [
    'style-loader',
    'css-loader',
    {
      loader: 'postcss-loader',
      options: {
        ident: 'postcss',
        plugins: [
          require('postcss-import')(),
          require('stylelint')(),
          ...,
        ]
      }
    }
  ]
}

1.4.2. 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.

1.4.3. 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

  1. Add babel-plugin-add-module-exports to your configuration
  2. You need to have only one default export per style module

1.4.4. 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')
  ]
}

1.5. Maintainers


Michael Ciniawsky

Alexander Krasnoyarov
Copyright © tuzhu008 2017 all right reserved,powered by Gitbook该文件修订时间: 2017-11-24 18:04:40

results matching ""

    No results matching ""