LoginSignup
12
12

More than 5 years have passed since last update.

ExtractTextPluginの使い方(webpack)

Last updated at Posted at 2016-12-21

ExtractTextPluginでうまくいかなかったことがあったので

メモです。詳細なところまでは踏み込んでいません。

(2017.2.27 追記)この記事で扱っているwebpackのバージョンは1.14.0。webpack2ではちょっと使い方が違う模様。
https://webpack.js.org/guides/migrating/#extracttextwebpackplugin-breaking-change

ExtractTextPluginを使用し、本番環境ではhead内にスタイルを展開しないようにしようと試みていた。以下の様に設定していたけれど、失敗してしまっていた。

うまくいかなかった例

webpack.config.js
var ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = [{
中略
  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("stylesheets/style.css")
  ]
}]

こちらの設定で実行してみるとエラーがでる。

Module parse failed: 〜中略〜 Unexpected character '@' (1:0)
You may need an appropriate loader to handle this file type.

@import の@で躓いてるのかな… よくわからない。
次の行ではローダーが適切ではないようなことが指摘されている。

うまくいった例

以下のように設定を修正してみた。
相違点は、extractをクラスメソッドではなくインスタンス経由で実行したのと、cssをヘッダに展開する必要がないため style-loader を削除した。

webpack.config.js
var ExtractTextPlugin = require('extract-text-webpack-plugin')
  , extractTextPlugin = new ExtractTextPlugin('stylesheets/[name].css');

module.exports = {
  entry: {
    'index': [
      './src/javascripts/modules/main/indexmain.js'
    ],
    'others': [
      './src/javascripts/modules/main/othersmain.js'
    ]
  },
  output: {
    path: path.join(__dirname, 'dist/assets/'),
    filename: "javascripts/[name].bundle.js"
  },
  module: {
    loaders: [
      { test: /\.js$/, loaders: ['babel-loader'], exclude: /node_modules/},
      { test: /\.css$/, loader: extractTextPlugin.extract("css-loader")},
      { test: /\.scss$/, loader: extractTextPlugin.extract("css!sass")},
    ]
  },
  plugins: [
    extractTextPlugin
  ]
};

うまくいった。

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