From 424fcc2f0205bd20f33d99228a001b8fdb17507f Mon Sep 17 00:00:00 2001 From: Justin Gordon Date: Wed, 17 Sep 2025 15:31:30 -1000 Subject: [PATCH 1/2] Improve React on Rails documentation for v16 and coding agents MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## New Documentation - **troubleshooting-build-errors.md**: Comprehensive guide for webpack/build issues - Missing routes file error patterns and solutions - ProvidePlugin module resolution troubleshooting - Environment setup dependencies and workarounds - Agent-friendly diagnostic scripts and auto-fixes - **coding-agents-guide.md**: Structured workflows for AI coding agents - Version compatibility matrix - Installation and upgrade workflows with error detection - Auto-fix strategies for common issues - Emergency procedures and rollback guidance ## Updated Documentation - **upgrading-react-on-rails.md**: - Removed js:export from upgrade steps (it's a setup issue, not upgrade-specific) - Focused troubleshooting on actual upgrade-related issues - Added reference to comprehensive build errors guide - **getting-started.md**: Updated to use react_on_rails v16.0.0 - **home.md**: Added troubleshooting guide to navigation ## Key Improvements - Separated setup/installation issues from upgrade-specific issues - Provided agent-friendly automation and error detection - Enhanced troubleshooting with actionable solutions - Improved documentation discoverability These improvements make react_on_rails documentation more comprehensive and accessible for both human developers and AI coding agents. 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude --- docs/contributor-info/coding-agents-guide.md | 404 ++++++++++++++++++ docs/getting-started.md | 2 +- docs/guides/upgrading-react-on-rails.md | 13 + docs/home.md | 3 +- .../troubleshooting-build-errors.md | 252 +++++++++++ 5 files changed, 672 insertions(+), 2 deletions(-) create mode 100644 docs/contributor-info/coding-agents-guide.md create mode 100644 docs/javascript/troubleshooting-build-errors.md diff --git a/docs/contributor-info/coding-agents-guide.md b/docs/contributor-info/coding-agents-guide.md new file mode 100644 index 0000000000..674b172f1f --- /dev/null +++ b/docs/contributor-info/coding-agents-guide.md @@ -0,0 +1,404 @@ +# React on Rails Guide for Coding Agents + +This guide provides structured instructions for AI coding agents working with React on Rails projects. + +## Table of Contents + +- [Quick Reference](#quick-reference) +- [Installation Workflows](#installation-workflows) +- [Upgrade Workflows](#upgrade-workflows) +- [Troubleshooting Patterns](#troubleshooting-patterns) +- [Error Detection and Auto-fixes](#error-detection-and-auto-fixes) +- [Best Practices for Agents](#best-practices-for-agents) + +## Quick Reference + +### Version Compatibility Matrix + +| react_on_rails | Shakapacker | Webpack | Node.js | Ruby | +|----------------|-------------|---------|---------|------| +| v16.x | >= 6.0 | v5 | 20-22 | 3.2+ | +| v14.x | >= 6.0 | v5 | 18-20 | 2.7+ | +| v13.x | >= 6.0 | v5 | 16-18 | 2.7+ | + +### Essential Files to Check + +- `Gemfile` - React on Rails gem version +- `package.json` - React on Rails npm package version +- `config/webpack/` - Webpack configuration +- `app/javascript/` - JavaScript source files +- `app/javascript/utils/routes.js` - Generated routes file (critical) + +### Common Commands + +```bash +# Generate JavaScript routes (critical step) +bundle exec rails js:export + +# Install generator (review before applying) +rails generate react_on_rails:install + +# Build assets +npm run build + +# Start development server +bin/dev +``` + +## Installation Workflows + +### New Rails Application + +```bash +# 1. Create Rails app +rails new PROJECT_NAME --skip-javascript +cd PROJECT_NAME + +# 2. Install Shakapacker +bundle add shakapacker --strict +rails shakapacker:install + +# 3. Install React on Rails +bundle add react_on_rails --version=16.0.0 --strict + +# 4. Run generator +rails generate react_on_rails:install + +# 5. Install JavaScript dependencies +npm install + +# 6. Generate routes (if using js-routes) +bundle exec rails js:export + +# 7. Test build +npm run build +``` + +### Existing Rails Application + +```bash +# 1. Check prerequisites +ls Gemfile | grep -q shakapacker || echo "⚠️ Shakapacker required" + +# 2. Add React on Rails +bundle add react_on_rails --version=16.0.0 --strict + +# 3. Run generator (REVIEW CHANGES) +rails generate react_on_rails:install --dry-run +# If acceptable: +rails generate react_on_rails:install + +# 4. Install dependencies +bundle install +npm install + +# 5. Generate routes +bundle exec rails js:export + +# 6. Test +npm run build +``` + +## Upgrade Workflows + +### v14 to v16 Upgrade + +```bash +# 1. Update versions +sed -i 's/react_on_rails.*~> 14\.0/react_on_rails", "~> 16.0/' Gemfile +sed -i 's/"react-on-rails": "^14\./"react-on-rails": "^16./' package.json + +# 2. Install updates +bundle update react_on_rails +npm install + +# 3. Generate routes (critical) +bundle exec rails js:export + +# 4. Test build +npm run build + +# 5. Check for errors (see troubleshooting section) +``` + +### Pre-upgrade Checklist + +```bash +#!/bin/bash +echo "=== Pre-upgrade Checklist ===" + +# Check current versions +echo "Current react_on_rails gem:" +bundle show react_on_rails 2>/dev/null | grep "react_on_rails" || echo "Not installed" + +echo "Current react-on-rails npm:" +npm list react-on-rails 2>/dev/null | grep "react-on-rails" || echo "Not installed" + +# Check Shakapacker +echo "Shakapacker version:" +bundle show shakapacker 2>/dev/null | grep "shakapacker" || echo "⚠️ Shakapacker not found" + +# Check Node.js version +echo "Node.js version: $(node --version)" + +# Check for routes file +[ -f "app/javascript/utils/routes.js" ] && echo "✓ Routes file exists" || echo "⚠️ Routes file missing" + +# Test current build +echo "Testing current build..." +npm run build >/dev/null 2>&1 && echo "✓ Build succeeds" || echo "⚠️ Build fails" +``` + +## Troubleshooting Patterns + +### Error Pattern Recognition + +```bash +# Function to detect common error patterns +detect_error_type() { + local log_file="$1" + + if grep -q "Cannot read properties of undefined.*reading 'module'" "$log_file"; then + echo "MISSING_ROUTES_FILE" + elif grep -q "Error: Can't resolve.*\$app" "$log_file"; then + echo "WEBPACK_ALIAS_ERROR" + elif grep -q "Module not found.*react-on-rails" "$log_file"; then + echo "DEPENDENCY_MISSING" + elif grep -q "webpack.*incompatible" "$log_file"; then + echo "VERSION_INCOMPATIBLE" + else + echo "UNKNOWN" + fi +} +``` + +### Auto-fix Strategies + +```bash +# Auto-fix missing routes +fix_missing_routes() { + if [ ! -f "app/javascript/utils/routes.js" ]; then + echo "🔧 Generating missing routes file..." + bundle exec rails js:export + return $? + fi + return 0 +} + +# Auto-fix dependency issues +fix_dependencies() { + echo "🔧 Updating dependencies..." + bundle update react_on_rails + npm install +} + +# Auto-fix webpack cache +fix_webpack_cache() { + echo "🔧 Clearing webpack cache..." + rm -rf node_modules/.cache tmp/cache +} +``` + +## Error Detection and Auto-fixes + +### Common Error Scenarios + +#### 1. Missing Routes File + +**Detection:** +```regex +/Cannot read properties of undefined.*reading 'module'/ +/ProvidedDependencyTemplate\.apply/ +``` + +**Auto-fix:** +```bash +bundle exec rails js:export +``` + +#### 2. ProvidePlugin Module Missing + +**Detection:** +```regex +/Error: Can't resolve.*\$app/ +/Module not found.*utils\/routes/ +``` + +**Auto-fix:** +```bash +# Check if file exists, generate if missing +[ -f "app/javascript/utils/routes.js" ] || bundle exec rails js:export + +# Check webpack aliases +grep -q "\$app" config/webpack/*.js || echo "⚠️ Missing webpack alias" +``` + +#### 3. Version Incompatibility + +**Detection:** +```regex +/webpack.*incompatible/ +/peer dep.*react-on-rails/ +``` + +**Auto-fix:** +```bash +# Update to compatible versions +npm install react-on-rails@^16.0.0 +bundle update react_on_rails +``` + +### Diagnostic Script + +```bash +#!/bin/bash +# react_on_rails_diagnostic.sh +echo "=== React on Rails Diagnostic ===" + +# 1. Version check +echo "📋 Checking versions..." +RAILS_VERSION=$(bundle show react_on_rails | grep -o '[0-9]\+\.[0-9]\+\.[0-9]\+' || echo "not found") +NPM_VERSION=$(npm list react-on-rails 2>/dev/null | grep -o '[0-9]\+\.[0-9]\+\.[0-9]\+' || echo "not found") +echo "Gem version: $RAILS_VERSION" +echo "NPM version: $NPM_VERSION" + +# 2. File existence +echo "📁 Checking critical files..." +[ -f "app/javascript/utils/routes.js" ] && echo "✓ Routes file exists" || echo "❌ Routes file missing" +[ -f "config/webpack/webpack.config.js" ] && echo "✓ Webpack config exists" || echo "❌ Webpack config missing" + +# 3. Webpack configuration +echo "⚙️ Checking webpack configuration..." +if grep -q "ProvidePlugin" config/webpack/*.js; then + echo "✓ ProvidePlugin found" + if grep -q "Routes.*\$app" config/webpack/*.js; then + echo "✓ Routes provider configured" + else + echo "❌ Routes provider not configured" + fi +else + echo "❌ ProvidePlugin not found" +fi + +# 4. Build test +echo "🔨 Testing build..." +if npm run build >/dev/null 2>&1; then + echo "✓ Build successful" +else + echo "❌ Build failed" + echo "Running auto-fixes..." + + # Auto-fix missing routes + if [ ! -f "app/javascript/utils/routes.js" ]; then + echo "🔧 Generating routes..." + bundle exec rails js:export + fi + + # Retry build + if npm run build >/dev/null 2>&1; then + echo "✓ Build successful after auto-fix" + else + echo "❌ Build still failing - manual intervention required" + fi +fi +``` + +## Best Practices for Agents + +### 1. Always Verify Before Modifying + +```bash +# Before making changes, always check current state +bundle show react_on_rails +npm list react-on-rails +git status +``` + +### 2. Use Dry-run When Available + +```bash +# Test generator changes before applying +rails generate react_on_rails:install --dry-run +``` + +### 3. Incremental Changes + +```bash +# Make one change at a time for easier rollback +git add -A && git commit -m "Update react_on_rails gem" +# Test, then continue +git add -A && git commit -m "Update react_on_rails npm package" +``` + +### 4. Error Recovery + +```bash +# If upgrade fails, provide rollback instructions +git log --oneline -5 # Show recent commits for rollback reference +git checkout HEAD~1 -- Gemfile package.json # Rollback versions +``` + +### 5. Environment Considerations + +- Always run `rails js:export` in a Rails environment +- Database warnings during `rails js:export` are usually non-fatal +- Test builds don't require database connectivity + +### 6. Communication with Users + +When reporting status to users: + +```bash +echo "✅ React on Rails upgrade successful" +echo "📊 Build metrics: $(npm run build 2>&1 | grep -o '[0-9]\+ errors\|successfully')" +echo "⚠️ Note: Some TypeScript errors may be unrelated to react_on_rails" +echo "🔗 Next steps: Test your application with 'bin/dev'" +``` + +### 7. Documentation Updates + +After successful upgrades, suggest: + +- Update README with new version requirements +- Update CI/CD configurations if needed +- Document any custom webpack configurations + +--- + +## Emergency Procedures + +### If Build Completely Breaks + +1. **Rollback immediately:** + ```bash + git checkout HEAD~1 -- Gemfile package.json Gemfile.lock package-lock.json + bundle install + npm install + ``` + +2. **Identify the issue:** + ```bash + npm run build 2>&1 | tee build-error.log + ``` + +3. **Apply targeted fixes:** + - Missing routes: `rails js:export` + - Cache issues: `rm -rf node_modules/.cache tmp/cache` + - Dependencies: `bundle update && npm install` + +4. **Document the issue** for future reference + +### If Rails Environment Unavailable + +Use minimal commands: +```bash +# Skip database operations +DATABASE_URL=sqlite3:tmp/minimal.db rails js:export + +# Or use test environment +RAILS_ENV=test rails js:export +``` + +--- + +This guide ensures consistent, reliable React on Rails operations for coding agents while providing clear error recovery paths. \ No newline at end of file diff --git a/docs/getting-started.md b/docs/getting-started.md index 265f964891..d5f724e5e3 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -26,7 +26,7 @@ You may need to check [the instructions for installing into an existing Rails ap Please use [the latest version](https://rubygems.org/gems/react_on_rails) to ensure you get all the security patches and the best support. ```bash - bundle add react_on_rails --version=14.0.4 --strict + bundle add react_on_rails --version=16.0.0 --strict ``` Commit this to git (or else you cannot run the generator in the next step unless you pass the option `--ignore-warnings`). diff --git a/docs/guides/upgrading-react-on-rails.md b/docs/guides/upgrading-react-on-rails.md index 0979291084..00cc9eba1f 100644 --- a/docs/guides/upgrading-react-on-rails.md +++ b/docs/guides/upgrading-react-on-rails.md @@ -81,6 +81,19 @@ rails generate react_on_rails:install bundle exec rspec # or your test command ``` +### Common Upgrade Issues + +#### Build Fails with Module Resolution Errors + +**Symptoms:** Webpack cannot find modules referenced in your configuration + +**Solutions:** +1. Clear webpack cache: `rm -rf node_modules/.cache` +2. Verify all ProvidePlugin modules exist +3. Check webpack alias configuration + +For troubleshooting build errors, see the [build errors guide](../javascript/troubleshooting-build-errors.md). + ### Enhanced Features in v16 - **Enhanced error handling** in `react_on_rails:generate_packs` task with detailed debugging guidance diff --git a/docs/home.md b/docs/home.md index 8493292b2e..4c363521ee 100644 --- a/docs/home.md +++ b/docs/home.md @@ -13,7 +13,8 @@ ## Changes and Upgrades 1. [CHANGELOG.md](https://github.com/shakacode/react_on_rails/tree/master/CHANGELOG.md) -2. [Upgrading React on Rails](./guides/upgrading-react-on-rails.md#upgrading-to-v12). +2. [Upgrading React on Rails](./guides/upgrading-react-on-rails.md) +3. [Troubleshooting Build Errors](./javascript/troubleshooting-build-errors.md) ## Example Apps diff --git a/docs/javascript/troubleshooting-build-errors.md b/docs/javascript/troubleshooting-build-errors.md new file mode 100644 index 0000000000..21b251d1df --- /dev/null +++ b/docs/javascript/troubleshooting-build-errors.md @@ -0,0 +1,252 @@ +# Troubleshooting Build Errors + +This guide covers common webpack build errors encountered when using react_on_rails and how to resolve them. + +## Table of Contents + +- [Missing Routes File Error](#missing-routes-file-error) +- [ProvidePlugin Module Resolution Errors](#provideplugin-module-resolution-errors) +- [Environment Setup Dependencies](#environment-setup-dependencies) +- [Shakapacker Compatibility Issues](#shakapacker-compatibility-issues) +- [For Coding Agents](#for-coding-agents) + +## Missing Routes File Error + +### Error Message +``` +Cannot read properties of undefined (reading 'module') +TypeError: Cannot read properties of undefined (reading 'module') + at ProvidedDependencyTemplate.apply +``` + +### Root Cause +This error typically occurs when webpack's `ProvidePlugin` cannot resolve a module reference. A common case is when the Rails routes file hasn't been generated for JavaScript consumption. + +### Solution +1. **Generate JavaScript routes file:** + ```bash + bundle exec rails js:export + ``` + +2. **Verify the routes file was created:** + ```bash + ls app/javascript/utils/routes.js + ``` + +3. **Check webpack configuration:** + Ensure your webpack config has the correct ProvidePlugin setup: + ```javascript + new webpack.ProvidePlugin({ + Routes: "$app/utils/routes" + }) + ``` + +4. **Verify alias configuration:** + ```javascript + resolve: { + alias: { + $app: path.join(rootPath, "app/javascript"), + } + } + ``` + +### Prevention +- Always run `rails js:export` after initial setup +- Include this step in your development setup documentation +- Consider adding it to your `package.json` setup script: + ```json + { + "scripts": { + "setup": "bundle exec rails js:export && npm install" + } + } + ``` + +## ProvidePlugin Module Resolution Errors + +### Common Error Patterns +- `Cannot read properties of undefined (reading 'module')` +- `Module not found: Error: Can't resolve 'module_name'` +- `ERROR in ./path/to/file.js: Cannot find name 'GlobalVariable'` + +### Debugging Steps + +1. **Check file existence:** + ```bash + find app/javascript -name "routes.*" -type f + find app/javascript -name "*global*" -type f + ``` + +2. **Verify webpack aliases:** + ```javascript + // In your webpack config + console.log('Webpack aliases:', config.resolve.alias); + ``` + +3. **Test module resolution:** + ```bash + # Run webpack with debug output + bin/shakapacker --debug-shakapacker + ``` + +4. **Check for circular dependencies:** + ```bash + # Install circular dependency plugin + npm install --save-dev circular-dependency-plugin + ``` + +### Common Fixes + +1. **Missing global modules:** Ensure all modules referenced in ProvidePlugin exist +2. **Incorrect paths:** Verify alias paths are correct relative to project root +3. **File extensions:** Make sure webpack can resolve the file extension + +## Environment Setup Dependencies + +### Rails Environment Required +Some react_on_rails operations require a working Rails environment: + +- `rails js:export` (generates routes) +- Asset precompilation +- Server-side rendering + +### Common Issues + +1. **Database Connection Errors:** + ``` + MONGODB | Error checking localhost:27017: Connection refused + ``` + + **Solution:** These are usually warnings and don't prevent operation. To silence: + ```bash + # Run with minimal environment + RAILS_ENV=development bundle exec rails js:export + ``` + +2. **Missing Dependencies:** + ``` + sidekiq-pro is not installed + ``` + + **Solution:** This is typically a warning for optional gems and won't affect builds. + +### Workarounds + +1. **Skip database initialization:** + ```bash + DATABASE_URL=sqlite3:tmp/db.sqlite3 rails js:export + ``` + +2. **Use test environment:** + ```bash + RAILS_ENV=test rails js:export + ``` + +## Shakapacker Compatibility Issues + +### Version Compatibility Matrix + +| react_on_rails | Shakapacker | Webpack | Node.js | +|----------------|-------------|---------|---------| +| v16.x | >= 6.0 | v5 | 20-22 | +| v14.x | >= 6.0 | v5 | 18-20 | +| v13.x | >= 6.0 | v5 | 16-18 | + +### Common Upgrade Issues + +1. **Webpacker to Shakapacker migration incomplete:** + ```bash + # Remove webpacker references + grep -r "webpacker" config/ + ``` + +2. **Old webpack configuration:** + ```bash + # Check for deprecated webpack configs + find config/webpack -name "*.js" -exec grep -l "webpacker" {} \; + ``` + +### Migration Steps +1. Follow the [Shakapacker upgrade guide](https://github.com/shakacode/shakapacker/blob/main/docs/v6_upgrade.md) +2. Update webpack configurations +3. Regenerate configurations with `rails generate react_on_rails:install` + +## For Coding Agents + +### Automated Diagnostics + +When encountering build errors, run this diagnostic script: + +```bash +#!/bin/bash +echo "=== React on Rails Build Diagnostics ===" + +echo "1. Checking versions..." +bundle show react_on_rails | grep "react_on_rails" +npm list react-on-rails 2>/dev/null | grep "react-on-rails" + +echo "2. Checking required files..." +[ -f "app/javascript/utils/routes.js" ] && echo "✓ Routes file exists" || echo "✗ Routes file missing - run 'rails js:export'" + +echo "3. Checking webpack config..." +grep -q "ProvidePlugin" config/webpack/*.js && echo "✓ ProvidePlugin found" || echo "✗ ProvidePlugin not found" + +echo "4. Checking aliases..." +grep -q "\$app" config/webpack/*.js && echo "✓ App alias found" || echo "✗ App alias missing" + +echo "5. Testing build..." +npm run build 2>&1 | head -20 +``` + +### Quick Fixes Checklist + +For agents encountering build errors: + +1. ✅ **Generate routes:** `rails js:export` +2. ✅ **Check file existence:** Verify all ProvidePlugin modules exist +3. ✅ **Update dependencies:** `bundle update react_on_rails && npm install` +4. ✅ **Clear cache:** `rm -rf tmp/cache node_modules/.cache` +5. ✅ **Regenerate config:** `rails generate react_on_rails:install` (review before applying) + +### Error Pattern Recognition + +Common error patterns for automated detection: + +```regex +# Missing routes file +/Cannot read properties of undefined.*reading 'module'/ + +# ProvidePlugin issues +/Error: Can't resolve.*\$app/ + +# Version compatibility +/webpack.*incompatible/ + +# Missing dependencies +/Module not found.*react-on-rails/ +``` + +### Automated Solutions + +```bash +# Auto-fix missing routes +if ! [ -f "app/javascript/utils/routes.js" ]; then + echo "Generating missing routes file..." + bundle exec rails js:export +fi + +# Auto-fix dependency issues +if grep -q "Cannot read properties" build.log; then + echo "Updating dependencies..." + bundle update react_on_rails + npm install +fi +``` + +--- + +## Need More Help? + +- Check the [general troubleshooting guide](./troubleshooting-when-using-shakapacker.md) +- Review [webpack configuration docs](./webpack.md) +- Contact [justin@shakacode.com](mailto:justin@shakacode.com) for professional support \ No newline at end of file From ed7975c9d7738694c4e829c283d0e93e61e21266 Mon Sep 17 00:00:00 2001 From: Justin Gordon Date: Wed, 17 Sep 2025 15:39:33 -1000 Subject: [PATCH 2/2] Clarify js-routes as optional dependency in documentation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Problem Documentation gave the impression that js-routes was a core react_on_rails requirement, when it's actually an optional integration used only in specific scenarios. ## Changes Made ### troubleshooting-build-errors.md - Added clear note that missing routes error only occurs with js-routes gem - Explained when js-routes IS and ISN'T needed - Provided alternative solution: remove ProvidePlugin if not using js-routes - Distinguished modern SPA patterns from Rails-heavy integration patterns ### coding-agents-guide.md - Added "(if using js-routes gem)" qualifier to all js:export commands - Updated auto-fix functions to clarify js-routes context - Modified diagnostic scripts to indicate js-routes dependency ### Environment dependencies - Clarified that rails js:export is only needed for js-routes gem ## Result - Documentation now accurately reflects js-routes as optional - Developers won't be confused into thinking it's required for react_on_rails - Clear guidance on when to use js-routes vs modern alternatives - Better separation of concerns between react_on_rails core and optional integrations 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude --- docs/contributor-info/coding-agents-guide.md | 14 ++--- .../troubleshooting-build-errors.md | 61 ++++++++++--------- 2 files changed, 40 insertions(+), 35 deletions(-) diff --git a/docs/contributor-info/coding-agents-guide.md b/docs/contributor-info/coding-agents-guide.md index 674b172f1f..8fbe8ca5e7 100644 --- a/docs/contributor-info/coding-agents-guide.md +++ b/docs/contributor-info/coding-agents-guide.md @@ -92,7 +92,7 @@ rails generate react_on_rails:install bundle install npm install -# 5. Generate routes +# 5. Generate routes (if using js-routes gem) bundle exec rails js:export # 6. Test @@ -112,7 +112,7 @@ sed -i 's/"react-on-rails": "^14\./"react-on-rails": "^16./' package.json bundle update react_on_rails npm install -# 3. Generate routes (critical) +# 3. Generate routes (if using js-routes gem) bundle exec rails js:export # 4. Test build @@ -175,10 +175,10 @@ detect_error_type() { ### Auto-fix Strategies ```bash -# Auto-fix missing routes +# Auto-fix missing routes (only if using js-routes gem) fix_missing_routes() { if [ ! -f "app/javascript/utils/routes.js" ]; then - echo "🔧 Generating missing routes file..." + echo "🔧 Generating missing routes file (js-routes gem)..." bundle exec rails js:export return $? fi @@ -203,7 +203,7 @@ fix_webpack_cache() { ### Common Error Scenarios -#### 1. Missing Routes File +#### 1. Missing Routes File (js-routes gem) **Detection:** ```regex @@ -288,9 +288,9 @@ else echo "❌ Build failed" echo "Running auto-fixes..." - # Auto-fix missing routes + # Auto-fix missing routes (only if using js-routes gem) if [ ! -f "app/javascript/utils/routes.js" ]; then - echo "🔧 Generating routes..." + echo "🔧 Generating routes (js-routes gem)..." bundle exec rails js:export fi diff --git a/docs/javascript/troubleshooting-build-errors.md b/docs/javascript/troubleshooting-build-errors.md index 21b251d1df..400fac213d 100644 --- a/docs/javascript/troubleshooting-build-errors.md +++ b/docs/javascript/troubleshooting-build-errors.md @@ -10,7 +10,9 @@ This guide covers common webpack build errors encountered when using react_on_ra - [Shakapacker Compatibility Issues](#shakapacker-compatibility-issues) - [For Coding Agents](#for-coding-agents) -## Missing Routes File Error +## Missing Routes File Error (js-routes gem) + +**Note:** This error only occurs if you're using the optional `js-routes` gem to access Rails routes in JavaScript. ### Error Message ``` @@ -20,9 +22,25 @@ TypeError: Cannot read properties of undefined (reading 'module') ``` ### Root Cause -This error typically occurs when webpack's `ProvidePlugin` cannot resolve a module reference. A common case is when the Rails routes file hasn't been generated for JavaScript consumption. - -### Solution +This error occurs when: +1. Your webpack config references Rails routes via ProvidePlugin +2. The `js-routes` gem hasn't generated the JavaScript routes file +3. You're using `js-routes` integration but missing the generated file + +### When You Need js-routes +`js-routes` is **optional** and typically used when: +- Rails-heavy apps with React components that need to navigate to Rails routes +- Server-side rendered apps mixing Rails and React routing +- Legacy Rails apps migrating ERB views to React +- Apps using Rails routing patterns for RESTful APIs + +### When You DON'T Need js-routes +Most modern React apps use: +- Client-side routing (React Router) instead of Rails routes +- Hardcoded API endpoints or environment variables +- SPA (Single Page App) architecture with API-only Rails backend + +### Solution (if using js-routes) 1. **Generate JavaScript routes file:** ```bash bundle exec rails js:export @@ -33,34 +51,21 @@ This error typically occurs when webpack's `ProvidePlugin` cannot resolve a modu ls app/javascript/utils/routes.js ``` -3. **Check webpack configuration:** - Ensure your webpack config has the correct ProvidePlugin setup: +3. **Check webpack configuration includes ProvidePlugin:** ```javascript new webpack.ProvidePlugin({ Routes: "$app/utils/routes" }) ``` -4. **Verify alias configuration:** - ```javascript - resolve: { - alias: { - $app: path.join(rootPath, "app/javascript"), - } - } - ``` - -### Prevention -- Always run `rails js:export` after initial setup -- Include this step in your development setup documentation -- Consider adding it to your `package.json` setup script: - ```json - { - "scripts": { - "setup": "bundle exec rails js:export && npm install" - } - } - ``` +### Alternative Solution (if NOT using js-routes) +Remove the Routes ProvidePlugin from your webpack configuration: +```javascript +// Remove this line if you don't use js-routes +new webpack.ProvidePlugin({ + Routes: "$app/utils/routes" // ← Remove this +}) +``` ## ProvidePlugin Module Resolution Errors @@ -104,9 +109,9 @@ This error typically occurs when webpack's `ProvidePlugin` cannot resolve a modu ## Environment Setup Dependencies ### Rails Environment Required -Some react_on_rails operations require a working Rails environment: +Some operations require a working Rails environment: -- `rails js:export` (generates routes) +- `rails js:export` (generates routes - **only needed if using js-routes gem**) - Asset precompilation - Server-side rendering