Uncaught ReferenceError: require is not defined
Help us help you! Please choose one:
- [ ] My app crashes with
react-rails, so I've included the stack trace and the exact steps which make it crash. - [ ] My app doesn't crash, but I'm getting unexpected behavior. So, I've described the unexpected behavior and suggested a new behavior.
- [ ] I'm trying to use
react-railswith another library, but I'm having trouble. I've described my JavaScript management setup (eg, Sprockets, Webpack...), how I'm trying to use this other library, and why it's not working. - [X] I have another issue to discuss.
My project is currently set up with Rails 5, Webpacker and React-Rails and when I tried to render my react component I got the following error, "Uncaught ReferenceError: require is not defined". I am assuming this is an issue with the Webpack configuration. Is there someone that help determine the cause of this error and how to fix it? -- Thanks!
Link to repo: repo
Yikes, sorry to hear that! Can you please share:
- the full error message and stack trace
- the
react_component(...)call which fails - the source code for the component you want to render
Then maybe we can debug a bit!
I am also experiencing the same issue in my new Rails 5.1.3 app. I could make a test app to recreate it if that would help?
I have the same setup (Webpacker 3.0.1, Rails 5.1.4, react-rails) and get a similar error message after doing bundle update:
react.source.js:3 Uncaught ReferenceError: module is not defined
at
gem update rails
gem update webpacker
rails new foo --webpack
cd foo
echo 'gem "react-rails", git: "https://github.com/reactjs/react-rails.git"' >> Gemfile
rails webpacker:install
rails g react:install
rails g react:component Post name:string
echo '<%= react_component "Post", {name: "Tim"}, prerender: true %>' > app/views/home/index.html.erb
rails s
# open localhost:3000/home/index
I'm seeing Error: Cannot find module "react"
Interesting. Not quite the same as your error but yeah there's some issue there.
In my environment, I had fixed this error with replacing var to const. It looks like var hoisting causes this error.
const componentRequireContext = require.context("components", true)
const ReactRailsUJS = require("react_ujs")
ReactRailsUJS.useContext(componentRequireContext)
Closing the issue.