LoginSignup
12
9

More than 5 years have passed since last update.

Sass+globパターンの環境構築とコンパイルの覚書

Posted at

これやっといてーと修正投げられたあるウェブサイトのスタイルはSassで書かれていました。基本Javaとかでサーバーサイドの私ですが、せっかくなのでSassの環境構築とコンパイル方法を学びました。この記事はその覚書で、Sassの詳細な利用方法や記法などは記載していません。

環境

  • Node.js v9.4.0
  • MacBook Air (13-inch, Mid 2012)
  • macOS Sierra 10.12.6

Sassとglob

普通にコンパイルするとエラーになるので調べると、@import 'layout/**/*.scss';のようにglobパターンで複数のscssファイルがインポートがされていたためでした。Sassのデフォルトではサポートされていないようで、glob用のプラグインを利用する必要があるとのこと。

globについてはこちらで教えていただきました。
https://qiita.com/tonkotsuboy_com/items/67d9fd4d054a45af9f34

メインのscssはこのような内容

style.scss
@charset 'utf-8';

// Utils
//-----------------------------------------------------------
@import 'utils/var';
@import 'utils/fonts';
@import 'utils/mixin';

// Base
//-----------------------------------------------------------
@import 'base/reset';
@import 'base/default';

// Layout
//-----------------------------------------------------------
@import 'layout/**/*.scss';

// Page style
//-----------------------------------------------------------
@import 'pages/**/*.scss';

環境構築

以上を踏まえて、参考記事にもあるNode.jsの「node-sass-globbing」というプラグインでglobパターンが使えるように、そしてコンパイラは必須の「node-sass」を利用します。

npmの初期設定

npm init -y

node-sassとnode-sass-globbingのインストール

npm install node-sass --save
npm install node-sass-globbing --save

コンパイル

作成されたpackage.jsonにコンパイルするためのscriptを追加します。(少し省略)
参考記事のコメントに書かれている通り、--importerオプションでnode_modules/node-sass-globbing/index.jsを指定するのがミソ。

package.json
{
  "name": "scss",
  "version": "1.0.0",
  "scripts": {
    "build": "node-sass --importer node_modules/node-sass-globbing/index.js -o dist style.scss"
  },
  "dependencies": {
    "node-sass": "^4.11.0",
    "node-sass-globbing": "0.0.23"
  }
}

コンパイル実行

npm run build

コンパイルに成功すると「dist」というディレクトリにcssが作成されます。
あとは、node-sassのオプションで
圧縮したり--output-style compressed
ソースマップを作成したり--source-map true

最後に

node-sassは結構高速な印象でした。Sass素敵。

12
9
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
12
9