目的
Webpack 1, 2どちらでも動かせるように実装しなきゃいけない!つらい環境で、
Webpackのバージョンが1か2か判定をして実行する処理を分けたい
結論
webpack.optimize.OccurenceOrderPlugin
をfunction
で比較する
参考にしたリポジトリ
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.OccurenceOrderPlugin
がfunction
かどうか判定し
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によって修正されている。
Typo in OccurenceOrderPlugin #179
https://github.com/webpack/webpack/issues/179fixed #179 typo in OccurenceOrderPlugin
https://github.com/webpack/webpack/commit/48aad3eeee3424e9150cce8df92cb5467213f40c?w=1#diff-fd0105318540761bae6db3485f46cad8L5
ポイントとしては、この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, }, }), ]
これで、判定できた
まとめ
今からコーディングするならWebpack 2で書くので、あまり意識しなくていいけど、
なぜ差分が現れたのか知るのは大事ですね。
もっと簡単に判定できる方法あるのかな?