21
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

webpack の EnvironmentPlugin で十分だった

Last updated at Posted at 2016-11-16

これまで DefinePlugin でこう書いてました。

new webpack.DefinePlugin({
  'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
})

でも実は、 EnvironmentPlugin 使えば、こう書けるんです。

new webpack.EnvironmentPlugin([
  "NODE_ENV",
  "HOGE"
])

入力:

if (process.env.NODE_ENV === 'local') {
  console.log('local!')
}

if (process.env.NODE_ENV === 'dev') {
  console.log('dev!')
}

console.log(process.env.HOGE)

NODE_ENV=dev HOGE=fuga webpack としたときの出力:

if (false) {
  console.log('local!')
}

if (true) {
  console.log('dev!')
}

console.log(("fuga"))

デフォルト値を指定したければ webpack.config.js に process.env.HOGE = process.env.HOGE || 'hoge' こんな感じで書けば OK.

とにかく JSON.stringify がだるいし、自分の用途的には DefinePlugin 使う理由がなくなってしまいました。どうしても __HOGE__ とか定義したい人向けってことかなぁ。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?