LoginSignup
110
121

More than 5 years have passed since last update.

webpackを使ってsassをコンパイルできるようにしよう!

Posted at

背景

なぜかこれのやり方に関する記事が簡単にみつからず、”じゃあいいよ俺書くよ!”ってことでメモ。
(こんだけ記事がないと何か根本的に俺は間違っているのだろうかと内心ビクついてるので、何かお気付きの方いらっしゃいましたら容赦なくツッコミ下さい。)

元々はフロントのes6をコンパイルするためにwebpackを導入してみたので、sassもwebpackで処理できればいいなと。
あ、あとjsとcssは別ファイルに出力したいという要件を前提にやってます。特に明確な理由があるわけじゃないけど、気持ちの問題で^^

環境

node 0.12.10
webpack 1.12.14

手順

ここを参考にSEPARATE CSS BUNDLE

必要なライブラリをインストール

npm install style-loader css-loader sass-loader extract-text-webpack-plugin --save

webpack設定ファイルを編集

webpack.config.js
const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = [{
  entry: {
    bundle: './src/app.js'
  },
  output: {
    path: path.join(__dirname, 'public'),
    filename: '[name].js'
  },
  module: {
    loaders: [
      {
        loader: 'babel',
        exclude: /node_modules/,
        test: /\.js[x]?$/,
        query: {
          cacheDirectory: true,
          presets: ['react', 'es2015']
        }
      }
    ]
  }
}, {
  entry: {
    style: './src/stylesheets/main.js'
  },
  output: {
    path: path.join(__dirname, 'public/css'),
    filename: '[name].css'
  },
  module: {
    loaders: [
      {
        test: /\.css$/,
        loader: ExtractTextPlugin.extract("style-loader", "css-loader")
      },
      {
        test: /\.scss$/,
        loader: ExtractTextPlugin.extract("style-loader", "css-loader!sass-loader")
      }
    ]
  },
  plugins: [
        new ExtractTextPlugin("[name].css")
    ]
}];

ビルド!

webpack

終わり。
手順だけ見ると結構簡単ですね。
(まあすんなり出来るはずもなく以下のように悪戦苦闘しました。ご参考までに。)

手順にたどり着くまでに出会ったエラー達

1 Entry module みつからねーZO!

ERROR in Entry module not found: Error: Cannot resolve 'file' or 'directory' ./src/stylesheets in /path/to/current/dir

設定項目のentryをあまり理解せずにcss置くディレクトリにしたら発生。
普通にentrypointとなるjsファイル(中身はrequire('./main.scss')だけ)を置いて、指定してやったら治った。

2 module ねーZO!

Error: Cannot resolve module 'style-loader'

style-loaderをインストールしてなかった。。。手順通りやればここには出会わないはず。

3 Promise 定義されてねーZO!

ReferenceError: Promise is not defined

nodeのバージョンが古いと出現するらしい。
v0.12.10にアップ。

4 nodeバージョン変わってんじゃねーかYO!

ERROR in The `libsass` binding was not found in
This usually happens because your node version has changed.
    Run `npm rebuild node-sass` to build the binding for your current node version.

はい、さーせん。npm rebuild node-sass流して解決。

110
121
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
110
121