LoginSignup
50
42

More than 3 years have passed since last update.

npm-scriptsの練習メモ sassのコンパイルと圧縮をやってみる

Last updated at Posted at 2017-04-22

npm-scriptsの練習としてsassをコンパイルして圧縮するものを作ってみたメモです。
npm初心者です。iMacユーザー。間違えてたらごめんなさい。

npm-scripts って? -> npmのタスク管理機能。タスクランナー。
公式:https://docs.npmjs.com/misc/scripts

※前準備

  • npmとNode.jsのインストール。
  • 該当ディレクトリに移動しておく。(ここではwordpressのテーマファイル内を想定して書いてます)

Node.jsって? -> サーバーサイドのJavaScript
公式:https://nodejs.org/ja/
npm って? -> Node.jsのパッケージマネージャー
公式:https://www.npmjs.com

1. package.jsonを作る

npm init
で対話形式でpackage.jsonの項目を入力…するのが正式?だけど面倒なのでコピペで済ましちゃってもいい。

{
  "name": "myTest",
  "version": "0.0.1",
  "description": "sass compile and minify"
}

必要項目とかよく分かって無いけれどこんな感じ。(パッケージ入れたらWARNでrepositoryとlicenseが無いって怒られたから、それも書いたほうが良いらしい。逆を言えば無くても動きます。)

2. 必要なパッケージをインストール

グーグル先生に聞くとnode-sassがオススメらしいのでインストール。

2021/02/27追記: node-sassはもう非推奨なので、sass( https://www.npmjs.com/package/sass ) に切り替えましょうー!

npm install --save node-sass -> npm install --save sass

sassについては node-sass(LibSass)からsass(DartSass)への移行 - Photosynthesic blog などを参照してください。

--saveと書くと、package.jsonにdependenciesとして以下のように追加される。こうしておくと後で便利。

"dependencies": {
  "node-sass": "^4.5.2"
}

3. scriptを書く

package.jsonのscriptsのところに、"スクリプト名": "コマンド"て感じで、やりたいことを書いていく。スクリプト名って書いちゃったけれど「shell scriptのエイリアス」って言うのが正しいのかな。

sassをコンパイルする

node-sassの書き方は
node-sass [options] <input> [output] または cat <input> | node-sass > output だけどcat良くわかんないのでスルー。

ここではscssディレクトリ以下にsassのファイル、一個上のディレクトリにcssファイルがある想定で

"scripts": {
    "compile-sass": "node-sass --include-path scss scss/style.scss ../style.css"
}

とか書く。

sass(css)を圧縮する

ファイルの圧縮もnode-sassで出来る。末尾に--output-style compressed

"build": "node-sass --include-path scss scss/style.scss ../style.css --output-style compressed"

ファイルをwatchする

いちいちコマンド叩くのも面倒なのでwatchしてもらうためには -w でファイルでもディレクトリでもwatchしてくれる。

"node-sass --include-path scss scss/style.scss ../style.css -w"

など。
というわけで、こんなscriptに。

 "scripts": {
    "compile-sass": "node-sass --include-path scss scss/style.scss ../style.css",
    "build": "node-sass --include-path scss scss/style.scss ../style.css --output-style compressed",
    "watch": "node-sass --include-path scss scss/style.scss ../style.css -w"
 }

4. npm run で動かす

書いたscriptを npm run compile-sassという感じで呼び出す。
watchを停止するのはcontrol + Cで。

5. 再利用

こんな感じで作ったpackage.jsonを次のプロジェクトのディレクトリにコピペ(node_modules以下は除く)して
npm install
すると、必要なパッケージがインストールされて使えます。

感想

何よりもプロジェクトに最適なパッケージを探すのが大変な気がするので(今回みたいなシンプルなものでもnode-sassが色々出来ることが分かって無くて別のパッケージを入れたりしました)、先達の素晴らしいpackage.jsonを探し出すのが何よりな気がします。でもgulp使ってた時はnpmって何だこの赤いのぐらいのふわっふわな認識で触ってたので、少し理解が出来てよかったかなあ。

50
42
3

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
50
42