LoginSignup
12
17

More than 5 years have passed since last update.

最新Webpack(4.1.1)で普通にSassつかう

Last updated at Posted at 2018-03-21

Webpackの設定はバージョンによって書き方が変わり、それはそれはうざいので、4.1.1の場合はこんなん動くよ、という意味もかねて書いてみた。

PCはあんまり関係ないけど一応Macで作ってubuntuでも動きました。バージョンは2018/03/21現在のlatestである4.1.1を使います。ライブラリなのでCSSを残すため、extract-text-webpack-pluginを利用しますが、エラーでるのでnext使えとコミュニティでだれかが言ってました(適当

下ごしらえ

まずは、webpackと依存パッケージをnpm installします。

# sassというフォルダ名で作ります
mkdir sass && cd sass

# 必要な依存を-D(開発環境のみ使用)でnpm install
npm i -D webpack webpack-cli node-sass css-loader sass-loader extract-text-webpack-plugin@next

#extract-text-webpack-pluginは修正済みの@next版を使わないとエラー出ます

必要なファイルを作ります。

# めんどいのでまとめて、srcフォルダ(開発用)に編集するindex.jsやscssファイルとdistフォルダ(出力用)にルートドキュメントのindex.htmlを作成、ここは自由
mkdir src && touch src/index.js && touch src/style.scss && mkdir dist && touch dist/index.html

# 設定ファイルを作成
touch webpack.config.js

これにWebpackに関する設定をかきます

webpack.config.js
// 開発環境によって切り分ける際に使用するための定数を定義
const ExtractTextPlugin = require('extract-text-webpack-plugin');

const ENV = 'development';
const userSourceMap = (ENV === 'development');

module.exports = {
  mode: ENV,
  module: {
    rules: [
      {
        test: /\.scss/, // 対象となるファイルの拡張子
        use: ExtractTextPlugin.extract({
          use:
            [
            {
              loader: 'css-loader',
              options: {
                url: false,
                sourceMap: userSourceMap,
                importLoaders: 2
              },
            },
            {
              loader: 'sass-loader',
              options: {
                // ソースマップの利用有無
                sourceMap: userSourceMap,
              }
            }
          ]
        }),
      },
    ],
  },

  plugins: [
    new ExtractTextPlugin('style.css'),
  ],
};

Sassをためす

style.scssを以下のように編集します。

style.scss
div {
  h1 {
    display:none;
  }
}

これはつまり、divのなかに入っているh1は消えろ、という意味になります。
さらにindex.htmlを編集します。

index.html
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Sassためす</title>
    <link rel="stylesheet" href="style.css" />
    <script src="main.js"></script>
  </head>
  <body>
    <h1>僕は存在します</h1>
    <div>
      <h1>僕は消されます</h1>
    </div>
  </body>
</html>
index.js
import './style.scss'; //scssの読み込み

Scssが正常にコンパイルされれば、divの中のh1だけ消されます。
開発するときは以下のコマンドでwatchさせます

webpack --watch # --wacthをつけるとファイルの変更を読み取って自動でコンパイルしてくれる
open dist/index.html # Macしかできない芸当だけどubuntuとかは普通にブラウザでファイルひらけばok

エラーが出なければ、だいたいコンパイルできています。

スクリーンショット 2018-03-21 13.06.20.png

↑うまくいったときのすくしょ

まとめ

意外と面倒なので、コピペ用に近い。

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