8

I'm using the Webpacker gem with Rails 5.2, and would like to access the environment in the Front End by setting a NODE_ENV global variable.
This is my config/webpack/environment.js file :

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

// Bootstrap 3 has a dependency over jQuery:
const webpack = require('webpack')

environment.plugins.prepend('Provide',
  new webpack.ProvidePlugin({
    $: 'jquery',
    jQuery: 'jquery'
  })
)

module.exports = environment

I saw that I needed to add the following plugin to webpack to be able access the environment in the front-end :

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

But I don't know how to add it... I tried many options, including the line below and it always, either doesn't work, or break jQuery (i.e. Uncaught ReferenceError: jQuery is not defined) :

environment.plugins.prepend('Provide',
  new webpack.DefinePlugin({
    'NODE_ENV': JSON.stringify(process.env.NODE_ENV)
  })
)

1 Answer 1

2

It turns out you just need to prepend/append a new plugin and give it a different name that those of your other plugins. Now my config/webpack/environment.js looks like that:

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

// Bootstrap 3 has a dependency over jQuery:
const webpack = require('webpack')

environment.plugins.prepend('Provide',
  new webpack.ProvidePlugin({
    $: 'jquery',
    jQuery: 'jquery'
  })
)

environment.plugins.prepend('env',
  new webpack.DefinePlugin({
    'NODE_ENV': JSON.stringify(process.env.NODE_ENV)
  })
)


module.exports = environment

I can now access NODE_ENV from every js/jsx file !!


This answer was posted as an edit to the question Adding plugin to Webpack with Rails by the OP oruhtra under CC BY-SA 4.0.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.