简体   繁体   中英

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 (ie Uncaught ReferenceError: jQuery is not defined):

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM