LoginSignup
21

More than 5 years have passed since last update.

Webpack2でpostcssを使う

Posted at

課題

webpack2でビルドしてるプロジェクトでautoprefixerを使いたくなった. またcssは別抽出してまとめたい.
postcssとExtractTextWebpackPluginで対応しようとした.

webpack2(2.1.0-beta.26)でこれをしようとしたら色々とはまったのでそのときのまとめ.

以下手順

0.必要パッケージインストール

npm install --save-dev postcss postcss-loader autoprefixer 

postcssとwebpackからつかうloader加えてautoprefixerを入れる.
extract-text-webpack-pluginは@betaを付与して新しいのを入れる.

npm install --save-dev extract-text-webpack-plugin@beta

1.Loader設定

postcssを通すようにcssに関するruleを設定する.

参考サイト

webpack.base.conf.js
const ExtractTextPlugin = require('extract-text-webpack-plugin')

// ...

rules: [
      {
        test: /\.(css|scss)$/,
        loader: ExtractTextPlugin.extract({
          fallbackLoader: 'style-loader',
          loader:[
            'css-loader',
            'sass-loader',
            'postcss-loader'
          ]
        })
      },
      // other rules
      // ...
]

2.postcssの設定

postcss.config.jsを作り配置して動かそうとするとpostcss.config.jsを読めないのかエラーが出た. なかなか解決できなかったので別の方法を模索した
結果,webpack.LoaderOptionsPluginを利用しpostcssの設定を渡せるらしい. 

そこでpostcssの設定をこれで渡す.

webpack.base.conf.js
 plugins: [
    new webpack.LoaderOptionsPlugin({
      options: {
        postcss: [
          require('autoprefixer')({
            browsers: ['last 2 versions']
          })
        ]
      }
    }),
    // other plugins
    // ...
  ]

3.ExtractTextPluginの設定

出力時の設定をpluginsの中に追加

webpack.base.conf.js
plugins: [
  new ExtractTextPlugin({ filename: '[name].[hash].css', disable: false, allChunks: true }),
  // other plugins
  // ...
]

まとめ

上記設定をwebpackに書けばwebpack2でpostcssが使えた.
autoprefixerしか今回は入れていないが必要になったら色々入れていきたい.

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
21