mjohnston / envify-loader

envify loader for webpack

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

You don't need this loader

sokra opened this issue · comments

You don't need this loader for two reasons:

1. You don't need loaders that just wrap browserify transforms.

There is a loader that does that: transform-loader.

{
  module: {
    postLoaders: [
      {
        loader: "transform?envify"
      }
    ]
  }
}

2. The DefinePlugin offers the same functionality

{
  plugins: [
    new webpack.DefinePlugin({
      "process.env": Object.keys(process.env).reduce(function(o, k) {
        o[k] = JSON.stringify(process.env[k]);
        return o;
      }, {})
    }
  ]
}

Nitpick - Just to make it copy-paste ready :-)

{
  plugins: [
    new webpack.DefinePlugin({
      'process.env': Object.keys(process.env).reduce(function(o, k) {
        o[k] = JSON.stringify(process.env[k]);
        return o;
      }, {})
    })
  ]
}

There is also the EnvironmentPlugin:

{
  plugins: [
    new webpack.EnvironmentPlugin([
      "NODE_ENV",
      "WHITELIST", "ALL", "ENVIRONMENT", "VARS"
    ])
  ]
}

Please note, the DefinePlugin approach above is potentially extremely risky, be sure to implement some whitelisting. It replaces the text process.env with an object of every environment variable, which means your entire environment may be transcribed into your public facing JS!

Be very careful - it works like this:

// Before processing
process.env.MY_VAR

// After processing
{MY_VAR: 'value', POSTGRES_PASSWORD: 'security_leak'}.MY_VAR

@sokra, you may wish to make a note of this in your post for others.

Just for those coming to this thread later on, the postLoader + envify route is a bad idea, because it makes all your assets uncacheable, slowing down rebuilds considerably. Go with the DefinePlugin approach.

In a project I'm working on right now we already have too many process.env and if you don't want to eliminate or replace all those I did this small change to the code you guys are proposing:

const envifiedVars = Object.keys(envVars).reduce((obj, key) => {
  obj[`process.env.${key}`] = JSON.stringify(envVars[key])
  return obj
}, {})

envVars being whatever enviornment variables you may have, we have them in another file and we load them there