13
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Posted at

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

13
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?