Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding plugin to Webpack with Rails

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)
  })
)
like image 422
oruhtra Avatar asked Jul 03 '26 21:07

oruhtra


1 Answers

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.

like image 127
vinzee Avatar answered Jul 05 '26 10:07

vinzee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!