Sha256: 9e76844ea89ae649fe2d325134bd605ef2c653448d8663fb180d8d4e056adaed

Contents?: true

Size: 1.93 KB

Versions: 43

Compression:

Stored size: 1.93 KB

Contents

# Environment variables


Environment variables are supported out of the box in Webpacker. For example if
you run the webpack dev server like so:
```
FOO=hello BAR=world ./bin/webpack-dev-server
```

You can then reference these variables in your JavaScript app code with
`process.env`:

```js
console.log(process.env.FOO) // Compiles to console.log("hello")
```

You may want to store configuration in environment variables via `.env` files,
similar to the [dotenv Ruby gem](https://github.com/bkeepers/dotenv).

In development, if you use [Foreman](http://ddollar.github.io/foreman) or [Invoker](http://invoker.codemancers.com)
to launch the webpack server, both of these tools have basic support for a
`.env` file (Invoker also supports `.env.local`), so no further configuration
is needed.

However, if you run the webpack server without Foreman/Invoker, or if you
want more control over what `.env` files to load, you can use the
[dotenv npm package](https://github.com/motdotla/dotenv). Here is what you could
do to support a "Ruby-like" dotenv:

```
yarn add dotenv
```

```javascript
// config/webpack/environment.js

...
const { environment } = require('@rails/webpacker')
const webpack = require('webpack')
const dotenv = require('dotenv')

const dotenvFiles = [
  `.env.${process.env.NODE_ENV}.local`,
  '.env.local',
  `.env.${process.env.NODE_ENV}`,
  '.env'
]
dotenvFiles.forEach((dotenvFile) => {
  dotenv.config({ path: dotenvFile, silent: true })
})

environment.plugins.prepend('Environment', new webpack.EnvironmentPlugin(JSON.parse(JSON.stringify(process.env))))

module.exports = environment
```

**Warning:** using Foreman/Invoker and npm dotenv at the same time can result in
confusing behavior, in that Foreman/Invoker variables take precedence over
npm dotenv variables.

If you'd like to pass custom variables to the on demand compiler, use `Webpacker::Compiler.env` attribute.

```rb
Webpacker::Compiler.env['FRONTEND_API_KEY'] = 'your_secret_key'
```

Version data entries

43 entries across 43 versions & 3 rubygems

Version Path
webpacker-4.3.0 docs/env.md
webpacker-5.0.1 docs/env.md
webpacker-5.0.0 docs/env.md
jetpacker-0.4.2 docs/env.md
jetpacker-0.4.1 docs/env.md
jetpacker-0.4.0 docs/env.md
jetpacker-0.3.0 docs/env.md
jetpacker-0.2.0 docs/env.md
webpacker-4.2.2 docs/env.md
webpacker-4.2.1 docs/env.md
webpacker-4.2.0 docs/env.md
webpacker-4.1.0 docs/env.md
chatops-rpc-0.0.2 fixtures/chatops-controller-example/vendor/bundle/ruby/2.5.0/gems/webpacker-4.0.7/docs/env.md
chatops-rpc-0.0.1 fixtures/chatops-controller-example/vendor/bundle/ruby/2.5.0/gems/webpacker-4.0.7/docs/env.md
webpacker-4.0.7 docs/env.md
webpacker-4.0.6 docs/env.md
webpacker-4.0.5 docs/env.md
webpacker-4.0.4 docs/env.md
webpacker-4.0.3 docs/env.md
webpacker-4.0.2 docs/env.md