1

I have created an app which uses Rails and a React front-end (rails new my-app --webpack=react)

I've worked with Rails and React separately before but never when integrated this way.

As the app is served on rails s, my understanding is that this is essentially working as a rails app which is rendering React components, so I believe be that the environment variables would be defined in config/application.yml rather than a .env, but I have tried both and can't get access to them in the React components

What I have tried

I'm running the rails server as well as ./bin/webpack-dev-server, and also run "webpack --config webpack.config.js" before starting the servers.

My webpack.config.js

const Dotenv = require('dotenv-webpack');
const webpack = require('webpack');
const path = require('path');


module.exports = {
  entry: path.resolve(__dirname, '') + '/app/javascript/packs/index.jsx',
  plugins: [
    new Dotenv(),
    new webpack.DefinePlugin({
      PRODUCTION: JSON.stringify(true),
      VERSION: JSON.stringify('5fa3b9'),
      BROWSER_SUPPORTS_HTML5: true,
      TWO: '1+1',
      'typeof window': JSON.stringify('object'),
      'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
      'process.env.REACT_APP_LAST_FM_API_KEY': JSON.stringify('myApiKeyfs89fs08a0')
    })
  ],
    module: {
    rules: [
      { test: /\.jsx$/, use: {loader:'babel-loader'} },
      { test: /\.js$/, use: {loader:'babel-loader'} }
    ]
  },
  node: {fs:"empty"},
  output: {
    publicPath: '/'
  }
};

1 Answer 1

4

In the end, I didn't need to do any of the above things. I just needed the .env file and to add

const dotenv = require('dotenv')
dotenv.config()

to my config/webpack/development.js

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.