Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
12
Help us understand the problem. What is going on with this article?
@naoyashiga

PostCSSで簡単なプラグインを作ってみよう

More than 5 years have passed since last update.

PostCSSでプラグインを作ってみます。今回は簡単な置換を行います。

npm

gulpを使用することにします。

$npm install gulp postcss gulp-postcss  --save-dev

プラグイン作成

フォルダ構成

|-node_modules
|-build
   |---css
      |---style.css
|-src
   |---css
      |---style.css
|-gulpfile.js

ファイル準備

|-node_modules
   |---postcss-myplugin
      |---index.js

node_modules配下にオリジナルプラグインフォルダを作成します。ここでは「postcss-myplugin」というフォルダを作りました。

index.js

index.js
var postcss = require('postcss')

module.exports = postcss.plugin('myplugin', function() {
    return function(css) {
            css.walkDecls(function transformDecl(decl) {
            decl.value = decl.value.replace('💩', '#7F4A1E');
        });
    };
});

「💩」という絵文字を「#7F4A1E」に置換します。

gulpfile設定

gulpfile.js
var gulp = require('gulp'),
gulpPostcss = require('gulp-postcss'),
myPlugin = require("postcss-myplugin");

gulp.task('styles', function() {
  var processors = [
    myPlugin
  ];
  return gulp.src([
    'src/css/style.css',
  ])
  .pipe(gulpPostcss(processors))
  .pipe(gulp.dest('build/css'))
});

実行結果

$gulp styles

置換前

src/css/style.css
.test {
    background: 💩;
}

置換後

build/css/style.css
.test {
    background: #7F4A1E;
}

置換できました :v:

・参考
PostCSS Deep Dive: Create Your Own Plugin - Envato Tuts+ Web Design Tutorial
https://github.com/postcss/postcss/blob/master/docs/writing-a-plugin.md
https://github.com/postcss/postcss

12
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
naoyashiga
クリエイティブ開発者

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
12
Help us understand the problem. What is going on with this article?