LoginSignup
2
1

More than 5 years have passed since last update.

Webpackのバージョンが1か2か判定する

Last updated at Posted at 2017-02-12
1 / 13

目的

Webpack 1, 2どちらでも動かせるように実装しなきゃいけない!つらい環境で、
Webpackのバージョンが1か2か判定をして実行する処理を分けたい:thinking:


結論

webpack.optimize.OccurenceOrderPluginfunctionで比較する


参考にしたリポジトリ

Phenomic
https://github.com/MoOx/phenomic/

Phenomicについて
https://speakerdeck.com/trkw/phenomic


参考にしたファイル

https://github.com/MoOx/phenomic/blob/0.20.3/docs/webpack.config.js#L8-L10
* WARNING: this config is super ultra cool as it support both webpack 1 & 2
訳: 警告:この設定はWebpack 1、2の両方をサポートするのでスーパーウルトラクール です。

こんな書かれていたら、気になるので調べてみる


_utils/webpack-version/index.js

これは判定しているJavaScript

https://github.com/MoOx/phenomic/blob/0.20.3/src/_utils/webpack-version/index.js

import webpack from 'webpack'

export default () => (
  typeof webpack.optimize.OccurenceOrderPlugin === 'function'
  ? 1
  : 2
)

三項演算子で、webpack.optimize.OccurenceOrderPluginfunctionかどうか判定し
functionであれば1、でなければ2を返すという実装のよう


OccurenceOrderPlugin

そもそもこのOptimizeプラグインは、モジュールに振るIDの桁数をより短くすることでよりコードを圧縮するものですが、
Webpack 2ではこれがデフォルトとなっています。

What's new in webpack 2
https://gist.github.com/sokra/27b24881210b56bbaff7#occurrence-order


Webpack 1.14.0のこの実装を追っていくと、下記ファイルが見つかる

https://github.com/webpack/webpack/blob/v1.14.0/lib/optimize/OccurenceOrderPlugin.js

/*
  MIT License http://www.opensource.org/licenses/mit-license.php
  Author Tobias Koppers @sokra
*/
module.exports = require("./OccurrenceOrderPlugin");

このファイルのgitログを追っていくとoccurrenceのtypoだという
下記のIssueと下記のCommitによって修正されている。


:bulb: ポイントとしては、このtypoされたfunctionがWebpack 1のみに存在し、
Webpack 2には存在しないため、この判定ができること


webpack.config.js

実際に、この_utils/webpack-version/index.jsを利用するとこんな感じ

まずは、import

https://github.com/MoOx/phenomic/blob/0.20.3/docs/webpack.config.js#L11

import webpackVersion from "phenomic/lib/_utils/webpack-version"

webpackVersion()で条件文をコーディングする

https://github.com/MoOx/phenomic/blob/0.20.3/docs/webpack.config.js#L173-L191

webpackVersion() === 1
? []
: [
 // You should be able to remove the block below when the following
 // issue has been correctly handled (and postcss-loader supports
 // "plugins" option directly in query, see postcss-loader usage above)
 // https://github.com/postcss/postcss-loader/issues/99
 new webpack.LoaderOptionsPlugin({
   test: /\.css$/,
   options: {
     postcss: postcssPlugins,
     // required to avoid issue css-loader?modules
     // this is normally the default value, but when we use
     // LoaderOptionsPlugin, we must specify it again, otherwise,
     // context is missing (and css modules names can be broken)!
     context: __dirname,
   },
 }),
]

これで、判定できた:innocent:


まとめ

今からコーディングするならWebpack 2で書くので、あまり意識しなくていいけど、
なぜ差分が現れたのか知るのは大事ですね。

もっと簡単に判定できる方法あるのかな?

2
1
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
2
1