PostCSS
でCSSを処理するためのローダー。
最新バージョンを使用するにはwebpack v5が必要です。Webpack v4の場合は、postcss-loader v4をインストールする必要があります。
開始するには、postcss-loader
とpostcss
をインストールする必要があります
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
オプションがあります。その仕組みと設定方法については以下で説明します。
ソースマップでパスが間違ってしまう可能性があるため、from
、to
、map
オプションは指定しないことをお勧めします。ソースマップが必要な場合は、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.json
のpostcss
プロパティ.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.js
に postcss-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,
},
},
},
],
},
};
設定ファイルへのパスを指定できます。
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 の実装を決定します。ローカルにインストールされた postcss
の peerDependency
バージョンをオーバーライドします。
このオプションは、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" },
],
},
],
},
};
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
をインストールする必要があります
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
をインストールする必要があります
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
をインストールする必要があります
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
とは何ですか?こちら をお読みください。
postcss-loader
側では追加のオプションは必要ありません。それらを適切に機能させるには、css-loader
の importLoaders
オプションを追加してください。
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
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 を使用している場合は、セットアップが機能するために次の操作を行う必要があります。
babel-plugin-add-module-exports
を設定に追加します。- スタイルモジュールごとに **default** エクスポートは1つだけにする必要があります。
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()],
},
},
},
],
},
],
},
};
依存関係は、変更されたファイルでwebpackがいつ再コンパイルを実行する必要があるかを理解するために必要です。
依存関係を追加する方法は2つあります。
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 を使用できます。
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;
まだの方は、貢献ガイドラインを一読してください。