'Uncaught ReferenceError: process is not defined - React-Rails
Components aren't rendering because of the Uncaught ReferenceError error. The error is thrown in one of the React API files (see the code in question below). I'm using the react-rails gem and am trying to render a blank component called 'Test'.
The file from React API(line 3)
'use strict';
if (process.env.NODE_ENV === 'production') {
module.exports = require('./cjs/react.production.min.js');
} else {
module.exports = require('./cjs/react.development.js');
}
ERB Rendering Component
<div style="width:100vw">
<%= react_component('Test') %>
</div>
The Component
import React from "react";
import PropTypes from "prop-types";
export default class Test extends React.Component{
render(){
return (
<div>
test
</div>
)
}
}
The React API should render 'test' to the (v)dom.
Solution 1:[1]
React-rails gem uses webpacker
, so I would follow their documentation to make sure you source your environment variables correctly, particularly the portion involving the setup of dotenv files if you don't use webpack-dev-server:
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:
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.
Here is what you could do to support a "Ruby-like" dotenv:
yarn add dotenv
// 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
If you'd like to pass custom variables to the on-demand compiler, use Webpacker::Compiler.env
attribute.
Webpacker::Compiler.env['FRONTEND_API_KEY'] = 'your_secret_key'
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Yeysides |