コンテンツにスキップ
トップに戻る

Stylusでスタイリングを始めましょう

Node.jsがインストールされていれば、Stylusのインストールは非常に簡単です。お使いのプラットフォーム用のバイナリを入手し、Nodeのパッケージマネージャであるnpmも含まれていることを確認してください。

次に、ターミナルで次のように入力します。

# npm
$ npm install stylus -g

# pnpm
$ pnpm add -g stylus
# npm
$ npm install stylus -g

# pnpm
$ pnpm add -g stylus

以下の機能や、下記に記載されている機能を持つnodejs用の表現力豊かなCSS言語が必要な場合は、詳細についてGitHubにアクセスしてください。

Stylus CLI

Stylusには、StylusをCSSに変換するためのstylus実行ファイルが付属しています。

Usage: stylus [options] [command] [< in [> out]]
              [file|dir ...]

Commands:

  help [<type>:]<prop> Opens help info at MDC for <prop> in
                        your default browser. Optionally
                        searches other resources of <type>:
                        safari opera w3c ms caniuse quirksmode

Options:

  -i, --interactive       Start interactive REPL
  -u, --use <path>        Utilize the Stylus plugin at <path>
  -U, --inline            Utilize image inlining via data URI support
  -w, --watch             Watch file(s) for changes and re-compile
  -o, --out <dir>         Output to <dir> when passing files
  -C, --css <src> [dest]  Convert CSS input to Stylus
  -I, --include <path>    Add <path> to lookup paths
  -c, --compress          Compress CSS output
  -d, --compare           Display input along with output
  -f, --firebug           Emits debug infos in the generated CSS that
                          can be used by the FireStylus Firebug plugin
  -l, --line-numbers      Emits comments in the generated CSS
                          indicating the corresponding Stylus line
  -m, --sourcemap         Generates a sourcemap in sourcemaps v3 format
  --sourcemap-inline      Inlines sourcemap with full source text in base64 format
  --sourcemap-root <url>  "sourceRoot" property of the generated sourcemap
  --sourcemap-base <path> Base <path> from which sourcemap and all sources are relative
  -P, --prefix [prefix]   Prefix all css classes
  -p, --print             Print out the compiled CSS
  --import <file>         Import stylus <file>
  --include-css           Include regular CSS on @import
  -D, --deps              Display dependencies of the compiled file
  --disable-cache         Disable caching
  --hoist-atrules         Move @import and @charset to the top
  -r, --resolve-url       Resolve relative urls inside imports
  --resolve-url-nocheck   Like --resolve-url but without file existence check
  -V, --version           Display the version of Stylus
  -h, --help              Display help information
Usage: stylus [options] [command] [< in [> out]]
              [file|dir ...]

Commands:

  help [<type>:]<prop> Opens help info at MDC for <prop> in
                        your default browser. Optionally
                        searches other resources of <type>:
                        safari opera w3c ms caniuse quirksmode

Options:

  -i, --interactive       Start interactive REPL
  -u, --use <path>        Utilize the Stylus plugin at <path>
  -U, --inline            Utilize image inlining via data URI support
  -w, --watch             Watch file(s) for changes and re-compile
  -o, --out <dir>         Output to <dir> when passing files
  -C, --css <src> [dest]  Convert CSS input to Stylus
  -I, --include <path>    Add <path> to lookup paths
  -c, --compress          Compress CSS output
  -d, --compare           Display input along with output
  -f, --firebug           Emits debug infos in the generated CSS that
                          can be used by the FireStylus Firebug plugin
  -l, --line-numbers      Emits comments in the generated CSS
                          indicating the corresponding Stylus line
  -m, --sourcemap         Generates a sourcemap in sourcemaps v3 format
  --sourcemap-inline      Inlines sourcemap with full source text in base64 format
  --sourcemap-root <url>  "sourceRoot" property of the generated sourcemap
  --sourcemap-base <path> Base <path> from which sourcemap and all sources are relative
  -P, --prefix [prefix]   Prefix all css classes
  -p, --print             Print out the compiled CSS
  --import <file>         Import stylus <file>
  --include-css           Include regular CSS on @import
  -D, --deps              Display dependencies of the compiled file
  --disable-cache         Disable caching
  --hoist-atrules         Move @import and @charset to the top
  -r, --resolve-url       Resolve relative urls inside imports
  --resolve-url-nocheck   Like --resolve-url but without file existence check
  -V, --version           Display the version of Stylus
  -h, --help              Display help information

STDIOコンパイルの例

stylusは*stdin*から読み取り、*stdout*に出力します。例えば

$ stylus --compress < some.styl > some.css
$ stylus --compress < some.styl > some.css

ターミナルでStylusを試してみましょう。以下に入力して、__EOF__のためにCTRL-Dを押してください。

$ stylus
body
  color red
  font 14px Arial, sans-serif
$ stylus
body
  color red
  font 14px Arial, sans-serif

ファイルのコンパイル例

stylusはファイルとディレクトリも受け付けます。例えば、cssという名前のディレクトリは、同じディレクトリに.cssファイルをコンパイルして出力します。

$ stylus css
$ stylus css

以下は、./public/stylesheetsに出力します。

$ stylus css --out public/stylesheets
$ stylus css --out public/stylesheets

または、いくつかのファイル

$ stylus one.styl two.styl
$ stylus one.styl two.styl

開発目的では、生成されたCSSでStylusのファイル名と行番号を示すコメントを生成するために、linenosオプションを使用できます。

$ stylus --line-numbers <path>
$ stylus --line-numbers <path>

または、Firebug用のFireStylus拡張機能を使用する場合はfirebugオプションを使用します。

$ stylus --firebug <path>
$ stylus --firebug <path>

クラスのプレフィックス

stylus実行ファイルは、指定された[プレフィックス]--prefixオプションを使用することで、生成されたすべてのスタイルにプレフィックスを付ける方法を提供します。

$ stylus --prefix foo-
$ stylus --prefix foo-

このコードで使用すると

.bar
  width: 10px
.bar
  width: 10px

以下が得られます。

.foo-bar {
  width: 10px;
}
.foo-bar {
  width: 10px;
}

すべてのクラスには、挿入、拡張などを含め、プレフィックスが付けられます。

CSSの変換

CSSを簡潔なStylus構文に変換したい場合は、--cssフラグを使用します。

stdio経由

$ stylus --css < test.css > test.styl
$ stylus --css < test.css > test.styl

同じベース名の.stylファイルを出力します。

$ stylus --css test.css
$ stylus --css test.css

特定の宛先に出力します。

$ stylus --css test.css /tmp/out.styl
$ stylus --css test.css /tmp/out.styl

CSSプロパティのヘルプ

OS Xでは、stylus help <prop>を実行すると、デフォルトのブラウザが開き、指定された<prop>のヘルプドキュメントが表示されます。

$ stylus help box-shadow
$ stylus help box-shadow

インタラクティブシェル

Stylus REPL(Read-Eval-Print-Loop)または「インタラクティブシェル」を使用すると、ターミナルから直接Stylus式を試すことができます。

これは式でのみ機能します。セレクタなどではありません。シンプルに使用するには、-iまたは--interactiveフラグを追加します。

$ stylus -i
> color = white
=> #fff
> color - rgb(200,50,0)
=> #37cdff
> color
=> #fff
> color -= rgb(200,50,0)
=> #37cdff
> color
=> #37cdff
> rgba(color, 0.5)
=> rgba(55,205,255,0.5)
$ stylus -i
> color = white
=> #fff
> color - rgb(200,50,0)
=> #37cdff
> color
=> #fff
> color -= rgb(200,50,0)
=> #37cdff
> color
=> #37cdff
> rgba(color, 0.5)
=> rgba(55,205,255,0.5)

インポート内の相対URLの解決

デフォルトでは、Stylusはインポートされた.stylファイルのURLを解決しません。したがって、url("baz.png")を持つbar/bar.styl@import "bar/bar.styl"で持つfoo.stylがあった場合、結果のCSSでもurl("baz.png")になります。

ただし、--resolve-url(または単に-r)オプションを使用することで、この動作を変更して、結果のCSSでurl("bar/baz.png")を取得できます。

依存関係の一覧表示

--deps(または単に-D)フラグを使用して、コンパイルされたファイルの依存関係の一覧を取得できます。

たとえば、test.stylがあるとします。

@import 'foo'
@import 'bar'
@import 'foo'
@import 'bar'

そしてfoo.styl

@import 'baz'
@import 'baz'

実行

$ stylus --deps test.styl
$ stylus --deps test.styl

インポートパスのリストが表示されます

foo.styl
baz.styl
bar.styl
foo.styl
baz.styl
bar.styl

現在、これは動的に生成されたパスでは機能しないことに注意してください。.

プラグインの活用

この例では、nib Stylusプラグインを使用して、そのCLIの使用法を説明します。

linear-gradient()関数を使用するためにnibをインポートする次のStylusがあるとします。

@import 'nib'

body
  background: linear-gradient(20px top, white, black)
@import 'nib'

body
  background: linear-gradient(20px top, white, black)

stdio経由でstylus(1)を使用してレンダリングする最初の試みは次のようになります。

$ stylus < test.styl
$ stylus < test.styl

(Stylusはnibの場所を知らないため)次のエラーが発生します。

Error: stdin:3
  1|
  2|
> 3| @import 'nib'
  4|
  5| body
  6|   background: linear-gradient(20px top, white, black)
Error: stdin:3
  1|
  2|
> 3| @import 'nib'
  4|
  5| body
  6|   background: linear-gradient(20px top, white, black)

Stylus APIを提供するだけのプラグインの場合は、Stylus検索パスへのパスを追加できます。それには、--includeまたは-Iフラグを使用します。

$ stylus < test.styl --include ../nib/lib
$ stylus < test.styl --include ../nib/lib

以下に出力結果を示します。(お気づきかもしれませんが、gradient-data-uri()create-gradient-image()の呼び出しはリテラルとして出力されています。これは、プラグインがJavaScript APIを提供する場合、ライブラリのパスを公開するだけでは不十分なためです。ただし、純粋なStylus nib関数のみを使用したい場合は、問題ありません。)

body {
  background: url(gradient-data-uri(create-gradient-image(20px, top)));
  background: -webkit-gradient(linear, left top, left bottom, color-stop(0, #fff), color-stop(1, #000));
  background: -webkit-linear-gradient(top, #fff 0%, #000 100%);
  background: -moz-linear-gradient(top, #fff 0%, #000 100%);
  background: linear-gradient(top, #fff 0%, #000 100%);
}
body {
  background: url(gradient-data-uri(create-gradient-image(20px, top)));
  background: -webkit-gradient(linear, left top, left bottom, color-stop(0, #fff), color-stop(1, #000));
  background: -webkit-linear-gradient(top, #fff 0%, #000 100%);
  background: -moz-linear-gradient(top, #fff 0%, #000 100%);
  background: linear-gradient(top, #fff 0%, #000 100%);
}

そこで、必要なのは--useまたは-uフラグを使用することです。これは、nodeモジュールへのパス(.js拡張子の有無にかかわらず)を期待します。これはモジュールをrequire()し、関数がmodule.exportsとしてエクスポートされることを期待し、その関数はstyle.use(fn())を呼び出してプラグインを公開します(そのjs関数などを定義します)。

$ stylus < test.styl --use ../nib/lib/nib
$ stylus < test.styl --use ../nib/lib/nib

期待どおりの結果が得られます

body {
  background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAAUCAYAAABMDlehAAAABmJLR0QA/wD/AP+gvaeTAAAAI0lEQVQImWP4+fPnf6bPnz8zMH358oUBwkIjKJBgYGNj+w8Aphk4blt0EcMAAAAASUVORK5CYII=");
  background: -webkit-gradient(linear, left top, left bottom, color-stop(0, #fff), color-stop(1, #000));
  background: -webkit-linear-gradient(top, #fff 0%, #000 100%);
  background: -moz-linear-gradient(top, #fff 0%, #000 100%);
  background: linear-gradient(top, #fff 0%, #000 100%);
}
body {
  background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAAUCAYAAABMDlehAAAABmJLR0QA/wD/AP+gvaeTAAAAI0lEQVQImWP4+fPnf6bPnz8zMH358oUBwkIjKJBgYGNj+w8Aphk4blt0EcMAAAAASUVORK5CYII=");
  background: -webkit-gradient(linear, left top, left bottom, color-stop(0, #fff), color-stop(1, #000));
  background: -webkit-linear-gradient(top, #fff 0%, #000 100%);
  background: -moz-linear-gradient(top, #fff 0%, #000 100%);
  background: linear-gradient(top, #fff 0%, #000 100%);
}

プラグインに引数を渡す必要がある場合は、--withオプションを使用します。--withは任意の有効なjavascript式を評価し、その値をプラグインに渡します。例えば

$ stylus < test.styl --use ../node_modules/autoprefixer-stylus --with "{ browsers: ['ie 7', 'ie 8'] }"
$ stylus < test.styl --use ../node_modules/autoprefixer-stylus --with "{ browsers: ['ie 7', 'ie 8'] }"