LoginSignup
4

More than 5 years have passed since last update.

stylusとpostcssを併用する

Last updated at Posted at 2017-02-03

poststyle (postcssをstylusパッケージで使えるようラップしたもの)を使わず、
stylusとpostcssを併用しようと思い、
ごにょごにょ書いてました。

A:stylus -> css, B: css -> css
の流れで2回ソースマップの生成があります。

それらをA.map, B.mapとしたときに、、
A.map + B.map = C.mapが欲しい。(足し算はイメージです)

postcssのオプションで、ソースマップを渡すことができ、
書き方やディレクトリ構成によってはうまくマージしてくれるようなんですが、

なんかうまくマージされなかったので、
multi-stage-sourcemap というパッケージを使って、
(poststyleのコード見たら、その中でも使われてた)
C.mapを生成しました。
書き方、ドキュメント見ればわかるんですが、パラメーターの順番に注意です。
from B, to Aです。

var Cmap = require('multi-stage-sourcemap').transfer({
  fromSourceMap: Bmap
, toSourceMap: Amap
})

ごにょっと書いた全容です。タスクランナーって便利だなと思いました。

var fs = require('fs')
  , del = require('del')

  , pkg = JSON.parse(fs.readFileSync('package.json', 'utf8'))

  , stylus = require('stylus')
  , stylusStr = fs.readFileSync('./stylus/main.styl', 'utf8')

  , postcss = require('postcss')
  , autoprefixer = require('autoprefixer')
  , csswring = require('csswring')

  , msMaper = require('multi-stage-sourcemap').transfer
  , cssName = 'hello.css'
  ;

var style = stylus(stylusStr)
              .set('filename', './stylus/main.styl')
              .set('paths', ['./stylus/'])
              .set('sourcemap', {
                  'sourceRoot': '//localhost:' + pkg.config.server.dev.port
                , 'comment': false
                })
              ;

style.render(function(err, css){
  if (err) throw err;

  postcss([
      autoprefixer(pkg.config.stylus.autoprefixer)
    , csswring(pkg.config.stylus.csswring)
    ])
    .process(css, {
      from: 'main.css'
    , to: cssName
    , map: (pkg.config ? {inline: false, sourcesContent: false} : false)
    })
    .then(result => {
      // Clean up
      del.sync([pkg.config.path.app + 'css'], {'force': true})

      // Make directory
      mkdirp(pkg.config.path.app + 'css', function(err) {
        if (err) throw err;

        if (pkg.config.isDebug) {
          // Output sourcemap
          fs.writeFileSync(
            pkg.config.path.app + 'css/' + cssName + '.map'
          , msMaper({
               fromSourceMap: result.map.toString()
             , toSourceMap: style.sourcemap
             })
          , 'utf8'
          );
        }
        // Output css
        fs.writeFileSync('css/' + cssName, result.css);

        console.log('🍺  Compiled stylus!')
     })
   });

});

パッケージAが提供するAPIをラップしたBをラップしたCを使ったGulpのパッケージを使ってコンパイル、とかやってると、
Aがどう動いてるのかとか、どういうAPIを提供しているのかがわからず、
Aのバージョンアップで機能追加されたときに、B, C, Gulpパッケージのアップデートをまったり、いちいちプルリクすんの面倒だね
というブログ記事とかを読んで触発されてこんな面倒なことしています。

面倒です。

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
4