postcss-loader

免責事項 postcss-loaderコミュニティメンバーによって保守されているサードパーティパッケージであり、webpackと同じサポート、セキュリティポリシー、またはライセンスを持たない可能性があり、webpackによって保守されていません。

npm node tests coverage size

Webpackディスカッション: discussion

PostCSSチャット: chat-postcss

PostCSSでCSSを処理するためのローダー。

はじめに

最新バージョンを使用するにはwebpack v5が必要です。Webpack v4の場合は、postcss-loader v4をインストールする必要があります。

開始するには、postcss-loaderpostcssをインストールする必要があります

npm install --save-dev postcss-loader postcss

または

yarn add -D postcss-loader postcss

または

pnpm add -D postcss-loader postcss

次に、webpack設定にプラグインを追加します。例:

次の構成では、postcss-preset-envプラグインが使用されていますが、これはデフォルトではインストールされていません。

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-preset-env",
                    {
                      // Options
                    },
                  ],
                ],
              },
            },
          },
        ],
      },
    ],
  },
};

設定ファイルを使用した代替の使用法

postcss.config.js

module.exports = {
  plugins: [
    [
      "postcss-preset-env",
      {
        // Options
      },
    ],
  ],
};

ローダーは設定ファイルを自動的に検索します。

webpack.config.js

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

そして、お好みの方法でwebpackを実行します。

オプション

execute

タイプ

type execute = boolean;

デフォルト:undefined

CSS-in-JSでPostCSSパーサーのサポートを有効にします。JSスタイルを使用する場合は、postcss-jsパーサーを追加し、executeオプションを追加します。

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

https://github.com/webpack-contrib/postcss-loader/blob/master/src/config.d.tsファイルを参照してください。

タイプ

import type { Config as PostCSSConfig } from "postcss-load-config";
import type { LoaderContext } from "webpack";

type PostCSSLoaderContext = LoaderContext<PostCSSConfig>;

interface PostCSSLoaderAPI {
  mode: PostCSSLoaderContext["mode"];
  file: PostCSSLoaderContext["resourcePath"];
  webpackLoaderContext: PostCSSLoaderContext;
  env: PostCSSLoaderContext["mode"];
  options: PostCSSConfig;
}

export type PostCSSLoaderOptions =
  | PostCSSConfig
  | ((api: PostCSSLoaderAPI) => PostCSSConfig);

デフォルト:undefined

PostCSSオプションとプラグインを設定できます。

すべてのPostCSSオプションがサポートされています。設定ファイルには特別なconfigオプションがあります。その仕組みと設定方法については以下で説明します。

ソースマップでパスが間違ってしまう可能性があるため、fromtomapオプションは指定しないことをお勧めします。ソースマップが必要な場合は、sourcemapオプションを使用してください。

大規模なプロジェクトでは、ローダーのパフォーマンスを最適化するために、ローダー設定でpostcssOptionsを提供し、config: falseを指定することをお勧めします。このアプローチにより、コンパイル中に外部設定ファイルを複数回検索してロードする必要がなくなります。

object

pluginsを設定します

webpack.config.js (推奨)

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 (非推奨、次のメジャーリリースで削除されます)

module.exports = {
  module: {
    rules: [
      {
        test: /\.sss$/i,
        loader: "postcss-loader",
        options: {
          postcssOptions: {
            plugins: {
              "postcss-import": {},
              "postcss-short": { prefix: "x" },
            },
          },
        },
      },
    ],
  },
};

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"),
          },
        },
      },
    ],
  },
};

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,
          },
        },
      },
    ],
  },
};

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-preset-env",
                ],
              };
            }

            return {
              plugins: [
                ["postcss-short", { prefix: "x" }],
                "postcss-preset-env",
              ],
            };
          },
        },
      },
    ],
  },
};

config

タイプ

type config = boolean | string;

デフォルト:true

設定ファイルを使用してオプションを設定できます。設定ファイルで指定されたオプションはローダーに渡されたオプションと組み合わされ、ローダーオプションは設定のオプションを上書きします。

設定ファイル

ローダーは、次の場所で構成のためにディレクトリツリーを検索します

  • package.jsonpostcssプロパティ
  • JSONまたはYAML形式の.postcssrcファイル
  • .postcssrc.json.postcssrc.yaml.postcssrc.yml.postcssrc.js、または.postcssrc.cjsファイル
  • オブジェクトをエクスポートするpostcss.config.jsまたはpostcss.config.cjs CommonJSモジュール (推奨)
設定ファイルの例

object表記を使用する

postcss.config.js (推奨)

module.exports = {
  // You can specify any options from https://postcss.dokyumento.jp/api/#processoptions here
  // parser: 'sugarss',
  plugins: [
    // Plugins for PostCSS
    ["postcss-short", { prefix: "x" }],
    "postcss-preset-env",
  ],
};

function表記を使用する

postcss.config.js (推奨)

module.exports = (api) => {
  // `api.file` - path to the file
  // `api.mode` - `mode` value of webpack, please read https://webpack.dokyumento.jp/configuration/mode/
  // `api.webpackLoaderContext` - loader context for complex use cases
  // `api.env` - alias `api.mode` for compatibility with `postcss-cli`
  // `api.options` - the `postcssOptions` options

  if (/\.sss$/.test(api.file)) {
    return {
      // You can specify any options from https://postcss.dokyumento.jp/api/#processoptions here
      parser: "sugarss",
      plugins: [
        // Plugins for PostCSS
        ["postcss-short", { prefix: "x" }],
        "postcss-preset-env",
      ],
    };
  }

  return {
    // You can specify any options from https://postcss.dokyumento.jp/api/#processoptions here
    plugins: [
      // Plugins for PostCSS
      ["postcss-short", { prefix: "x" }],
      "postcss-preset-env",
    ],
  };
};

postcss.config.js (非推奨、次のメジャーリリースで削除されます)

module.exports = {
  // You can specify any options from https://postcss.dokyumento.jp/api/#processoptions here
  // parser: 'sugarss',
  plugins: {
    // Plugins for PostCSS
    "postcss-short": { prefix: "x" },
    "postcss-preset-env": {},
  },
};
構成カスケード

異なるディレクトリで異なる 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.jspostcss-loader を追加します。単独で使用することも、css-loader と組み合わせて使用することもできます(推奨)。

css-loader および style-loader **よりも前** に、ただし sass|less|stylus-loader のような他のプリプロセッサローダーを使用する場合は、それらのローダー**よりも後** に使用してください(webpackローダーは右から左/下から上へ評価されるため)。

webpack.config.js (推奨)

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

boolean

設定の自動読み込みを有効/無効にします。

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        loader: "postcss-loader",
        options: {
          postcssOptions: {
            config: false,
          },
        },
      },
    ],
  },
};

String

設定ファイルへのパスを指定できます。

webpack.config.js

const path = require("path");

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        loader: "postcss-loader",
        options: {
          postcssOptions: {
            config: path.resolve(__dirname, "custom.config.js"),
          },
        },
      },
    ],
  },
};

sourceMap

タイプ

type sourceMap = boolean;

デフォルト:compiler.devtool の値に依存します

デフォルトでは、ソースマップの生成は devtool オプションに依存します。eval および false 値を除くすべての値でソースマップの生成が有効になります。

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 } },
        ],
      },
    ],
  },
};

代替設定

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" },
        ],
      },
    ],
  },
};

implementation

タイプ

type implementation = object;

implementation の型は、postcss.d.ts と同じである必要があります。

デフォルト:postcss

特別な implementation オプションは、使用する PostCSS の実装を決定します。ローカルにインストールされた postcsspeerDependency バージョンをオーバーライドします。

このオプションは、PostCSS 7 から 8 への移行を容易にするために、ダウンストリームツール作成者にとってのみ実際に役立ちます。

function

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" },
        ],
      },
    ],
  },
};

String

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

sugarss をインストールする必要があります

npm install --save-dev sugarss

SugarSS 構文を使用します。

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",
              },
            },
          },
        ],
      },
    ],
  },
};

Autoprefixer

autoprefixer をインストールする必要があります

npm install --save-dev autoprefixer

autoprefixer を使用して、CSSルールにベンダープレフィックスを追加します。

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
                    },
                  ],
                ],
              },
            },
          },
        ],
      },
    ],
  },
};

警告

postcss-preset-env には autoprefixer が含まれているため、プリセットを既に使用している場合は、別途追加する必要はありません。詳細は こちら を参照してください。

PostCSS Preset Env

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
                    },
                  ],
                ],
              },
            },
          },
        ],
      },
    ],
  },
};

CSS Modules

CSS Modules とは何ですか?こちら をお読みください。

postcss-loader 側では追加のオプションは必要ありません。それらを適切に機能させるには、css-loaderimportLoaders オプションを追加してください。

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 と postcss-js

postcss-js をインストールする必要があります

npm install --save-dev postcss-js

JavaScript で記述されたスタイルを処理する場合は、postcss-js パーサーを使用してください。

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",
        ],
      },
    ],
  },
};

結果として、次のような方法でスタイルを記述できるようになります。

import colors from "./styles/colors";

export default {
  ".menu": {
    color: colors.main,
    height: 25,
    "&_link": {
      color: "white",
    },
  },
};

警告

Babel を使用している場合は、セットアップが機能するために次の操作を行う必要があります。

  1. babel-plugin-add-module-exports を設定に追加します。
  2. スタイルモジュールごとに **default** エクスポートは1つだけにする必要があります。

CSS の抽出

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",
    }),
  ],
};

アセットの出力

PostCSSプラグインからwebpackにアセットを書き込むには、result.messagesにメッセージを追加する必要があります。

メッセージには次のフィールドが含まれている必要があります。

  • type = asset - メッセージタイプ (必須、asset に等しい必要があります)
  • file - ファイル名 (必須)
  • content - ファイルの内容 (必須)
  • sourceMap - ソースマップ
  • info - アセット情報

webpack.config.js

const postcssCustomPlugin = (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()],
              },
            },
          },
        ],
      },
    ],
  },
};

依存関係、contextDependencies、buildDependencies、missingDependencies の追加

依存関係は、変更されたファイルでwebpackがいつ再コンパイルを実行する必要があるかを理解するために必要です。

依存関係を追加する方法は2つあります。

  1. (推奨)プラグインは result.messages でメッセージを送信できます。

メッセージには次のフィールドが含まれている必要があります。

  • type = dependency - メッセージタイプ (必須、dependency, context-dependency, build-dependency または missing-dependency に等しい必要があります)
  • file - 絶対ファイルパス (必須)

webpack.config.js

const path = require("path");

const postcssCustomPlugin = (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()],
              },
            },
          },
        ],
      },
    ],
  },
};

または、既製のプラグイン postcss-add-dependencies を使用できます。

  1. プラグインに loaderContext を渡します。

webpack.config.js

const path = 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"),
              },
            },
          },
        ],
      },
    ],
  },
};

postcss.config.js

module.exports = (api) => ({
  plugins: [
    require("path/to/postcssCustomPlugin.js")({
      loaderContext: api.webpackLoaderContext,
    }),
  ],
});

postcssCustomPlugin.js

const path = require("path");

const postcssCustomPlugin = (opts = {}) => {
  return {
    postcssPlugin: "postcss-custom-plugin",
    Once: (root, { result }) => {
      opts.loaderContext.addDependency(
        path.resolve(__dirname, "path", "to", "file"),
      );
    },
  };
};

postcssCustomPlugin.postcss = true;
module.exports = postcssCustomPlugin;

貢献

まだの方は、貢献ガイドラインを一読してください。

貢献

ライセンス

MIT