Webpacker: Pass custom environment variables to the compiler

Created on 24 Aug 2017  路  11Comments  路  Source: rails/webpacker

Given deployment flow using Capistrano, one would like to pass custom environment variables, like current revision hash or some access tokens (to upload source map to Rollbar or API key for Google Maps) to Webpack, so it can compile them into generated code.

I suppose it could be done by extending webpack_env method on Webpacker::Compiler?

Most helpful comment

I'm having the same issue as @nozpheratu - setting variables with Webpacker::Compiler.env doesn't seem to make it into the actual javascript environment. Anyone have a suggestion? Did this break somewhere?

All 11 comments

@sjchmiela Good Point 馃憤 We probably wanna expose an env accessor like watched_paths to extend default env variables on compiler.

Webpacker::Compiler.env['FOO'] = 'bar'

=> Webpacker.compiler.env
=> { ASSET_HOST: 'x', FOO: 'bar', ....}

cc// @dhh

That sounds reasonable to me 馃憤

Great! 馃憤 I'll submit a PR in a couple of hours.

@sjchmiela if you don't mind me asking, how does one use this with capistrano? Specifically for setting current_revision.

I ended up doing

if File.exist?('REVISION')
  Webpacker::Compiler.env['CURRENT_REVISION'] = File.read('REVISION').strip
end

in my application.rb.
May be gonna be useful for someone, unless there's a better suggestion.

I've ended up using something similar:

# config/initializers/revision.rb
git_sha, = Open3.capture3('git rev-parse HEAD')
revision, _, revision_status = Open3.capture3('cat REVISION')

HealthNation::Application::REVISION =
  if revision_status.success?
    revision.chomp
  else
    git_sha.chomp
  end

and in initializers/webpacker.rb

Webpacker::Compiler.env['VERSION'] = HealthNation::Application::REVISION

@sjchmiela I see, thank you for responding!

I noticed custom environments variables defined in this manner don't seem to be made available to Webpacker-compiled JavaScript via the process.env directive -- would I be wrong to assume that a file defined in initializers/webpacker.rb with the contents:

Webpacker::Compiler.env['VERSION'] = '1.0'

should assign process.env.VERSION in JavaScript?

I'm having the same issue as @nozpheratu - setting variables with Webpacker::Compiler.env doesn't seem to make it into the actual javascript environment. Anyone have a suggestion? Did this break somewhere?

@bbugh Could you please file a separate issue for this one so we can test and push a fix?

@gauravtiwari Whoops, sorry - I thought this one was still open. Too many related tabs. I will make another issue.

Was this page helpful?
0 / 5 - 0 ratings