### Install Multiple JavaScript Libraries (Example) Source: https://github.com/praxis-emergent/islandjs-rails/blob/main/README.md Illustrates the command-line usage for installing various UMD-compatible JavaScript libraries through IslandJS Rails. This approach avoids complex build configurations by directly using UMD packages, making it easy to add libraries like `react-beautiful-dnd`, `quill`, `recharts`, and `lodash`. ```bash # Instead of complex build configuration: rails "islandjs:install[react,19.1.0]" rails "islandjs:install[react-beautiful-dnd]" rails "islandjs:install[quill]" rails "islandjs:install[recharts]" rails "islandjs:install[lodash]" ``` -------------------------------- ### Install Packages via Rails CLI Source: https://context7.com/praxis-emergent/islandjs-rails/llms.txt Install React, React DOM, and other third-party libraries using the `rails islandjs:install` command. This command automatically downloads UMD builds and configures Vite. You can specify versions or install the latest version. ```bash # Initialize IslandJS in your Rails project rails islandjs:init # Install React and React DOM rails "islandjs:install[react,19.1.0]" rails "islandjs:install[react-dom,19.1.0]" # Install third-party libraries rails "islandjs:install[lodash,4.17.21]" rails "islandjs:install[@solana/web3.js,1.98.4]" # Install without specific version (uses latest) rails "islandjs:install[chart.js]" # Check installation status rails islandjs:status # Output: # ✓ react (19.1.0) - UMD available at /vendor/islands/react-19.1.0.min.js # ✓ react-dom (19.1.0) - UMD available at /vendor/islands/react_dom-19.1.0.min.js # ✓ lodash (4.17.21) - UMD available at /vendor/islands/lodash-4.17.21.min.js ``` -------------------------------- ### Install Scoped Packages with Rails Task Source: https://github.com/praxis-emergent/islandjs-rails/blob/main/README.md Demonstrates how to use the `rails islandjs:install` command to add scoped JavaScript packages. It highlights the necessity of using double quotes around package names containing special characters like '@' to ensure proper shell interpretation. The examples show installation with and without specifying a version. ```bash # ✅ Works perfectly rails "islandjs:install[@solana/web3.js]" # ✅ Also works (with version) rails "islandjs:install[@solana/web3.js,1.98.4]" # ⚠️ May not work in some shells without quotes rails islandjs:install[@solana/web3.js] # Avoid this ``` -------------------------------- ### Package Installation (CLI) Source: https://context7.com/praxis-emergent/islandjs-rails/llms.txt Install packages and their UMD versions into your Rails project using the provided `rails` commands. This also configures Vite automatically. ```APIDOC ## Package Installation (CLI) Install a package with automatic UMD download and Vite configuration. ```bash # Initialize IslandJS in your Rails project rails islandjs:init # Install React and React DOM rails "islandjs:install[react,19.1.0]" rails "islandjs:install[react-dom,19.1.0]" # Install third-party libraries rails "islandjs:install[lodash,4.17.21]" rails "islandjs:install[@solana/web3.js,1.98.4]" # Install without specific version (uses latest) rails "islandjs:install[chart.js]" # Check installation status rails islandjs:status # Output: # ✓ react (19.1.0) - UMD available at /vendor/islands/react-19.1.0.min.js # ✓ react-dom (19.1.0) - UMD available at /vendor/islands/react_dom-19.1.0.min.js # ✓ lodash (4.17.21) - UMD available at /vendor/islands/lodash-4.17.21.min.js ``` ``` -------------------------------- ### Installing Scoped npm Packages with IslandJS Rails (Bash) Source: https://github.com/praxis-emergent/islandjs-rails/blob/main/README.md This snippet demonstrates the correct syntax for installing scoped npm packages (e.g., `@solana/web3.js`) using the IslandJS Rails CLI. It highlights the necessity of including the full package name with the scope and `.js` suffix to avoid installation errors. ```bash # ✅ Correct - Full scoped package name rails "islandjs:install[@solana/web3.js,1.98.4]" # ❌ Incorrect - Missing .js suffix rails "islandjs:install[@solana/web3,1.98.4]" # ❌ Incorrect - Missing scope rails "islandjs:install[web3.js,1.98.4]" ``` -------------------------------- ### Run IslandJS Rails Tests Source: https://github.com/praxis-emergent/islandjs-rails/blob/main/README.md Provides instructions for running the tests for the IslandJS Rails gem. It includes steps to install dependencies, execute the tests using RSpec, and view coverage reports both in the terminal and by opening an HTML report in the browser. ```bash cd lib/islandjs_rails bundle install bundle exec rspec # View coverage in terminal bundle exec rspec # Open coverage report in browser open coverage/index.html ``` -------------------------------- ### Install JavaScript Libraries with IslandJS Rails Source: https://github.com/praxis-emergent/islandjs-rails/blob/main/README.md Demonstrates how to install specific JavaScript libraries, like React, using the `islandjs:install` Rails generator. This command fetches UMD versions of libraries and makes them available for use in your Rails application. Currently, React is limited to version 19.1.0 due to upstream UMD packaging limitations. ```bash rails "islandjs:install[react,19.1.0]" rails "islandjs:install[react-dom,19.1.0]" ``` -------------------------------- ### Render React Component with Options Source: https://github.com/praxis-emergent/islandjs-rails/blob/main/README.md Shows how to render a React component using the `react_component` helper in ERB. It includes an example with specific props and options, such as `container_id` and `namespace`, demonstrating customization for component rendering and access. ```erb <%= react_component('UserProfile', { userId: current_user.id, theme: 'dark' }, { container_id: 'profile-widget', namespace: 'window.islandjsRails' }) %> ``` -------------------------------- ### Manage IslandJS Packages Programmatically (Ruby API) Source: https://context7.com/praxis-emergent/islandjs-rails/llms.txt Manage installed packages using the IslandjsRails Ruby API. Functions include installing, updating, removing, syncing packages from `package.json`, checking installation status, detecting global names, and cleaning vendor files. ```ruby # Install a package IslandjsRails.install!('react', '19.1.0') # Update package to new version IslandjsRails.update!('react', '19.1.0') # Remove package IslandjsRails.remove!('lodash') # Sync all packages from package.json IslandjsRails.sync! # Check if package is installed if IslandjsRails.package_installed?('react') version = IslandjsRails.version_for('react') puts "React #{version} is installed" end # Get global name for a library global_name = IslandjsRails.detect_global_name('@solana/web3.js') # => "solanaWeb3" # Clean all vendor files and rebuild IslandjsRails.clean! ``` -------------------------------- ### Development Server for Islands Source: https://github.com/praxis-emergent/islandjs-rails/blob/main/README.md Command to start the development server for your React islands using yarn. This command, `yarn watch:islands`, is essential during development to enable hot-reloading and efficient management of your frontend components. ```bash yarn watch:islands ``` -------------------------------- ### Install Third-Party Libraries with Island.js Source: https://context7.com/praxis-emergent/islandjs-rails/llms.txt Install third-party JavaScript libraries, such as Chart.js, into your Rails project using the provided Island.js generator command. This command specifies the library name and version to be installed. ```bash # Install Chart.js for data visualization rails "islandjs:install[chart.js,4.4.0]" ``` -------------------------------- ### Add IslandJS Rails Gem Source: https://github.com/praxis-emergent/islandjs-rails/blob/main/README.md This snippet shows how to add the islandjs-rails gem to your Rails application's Gemfile. After adding the gem, run `bundle install` to install it and then execute the `rails islandjs:init` command to initialize the gem in your project. ```ruby # Add to your Gemfile gem 'islandjs-rails' ``` -------------------------------- ### Create a Basic React Counter Component for Islands Source: https://context7.com/praxis-emergent/islandjs-rails/llms.txt Example of defining a simple React component intended for use with Island.js in a Rails application. This component is compatible with Turbo and includes basic state management using `useState`. ```jsx // app/javascript/islands/components/Counter.jsx import React, { useState } from 'react'; function Counter({ containerId }) { const [count, setCount] = useState(0); return (
); } export default Counter; ``` -------------------------------- ### Sync Vite Externals with Rails IslandJS Source: https://github.com/praxis-emergent/islandjs-rails/blob/main/README.md Demonstrates the command-line interface (CLI) commands for managing IslandJS Rails and its Vite integration. `rails islandjs:sync` is used to update Vite externals, while `rails islandjs:clean` and `rails islandjs:install` can be used for cleaning and reinstalling specific packages. ```bash # Sync to update externals rails islandjs:sync # Or clean and reinstall rails islandjs:clean rails islandjs:install[react] ``` -------------------------------- ### Troubleshooting Package Not Found Source: https://github.com/praxis-emergent/islandjs-rails/blob/main/README.md Provides troubleshooting steps for the 'Package not found' error when using IslandJS Rails with scoped packages. It emphasizes checking the exact package name on npm and ensuring the full, correct name is used in the `islandjs:install` command. ```bash # Check the exact package name on npm npm view @solana/web3.js # Ensure you're using the full name rails "islandjs:install[@solana/web3.js]" # ✅ Correct rails "islandjs:install[@solana/web3]" # ❌ Wrong ``` -------------------------------- ### Reinitialize IslandJS Rails with Vite Source: https://github.com/praxis-emergent/islandjs-rails/blob/main/UPGRADING.md This Rails generator command reinitializes IslandJS with Vite. It creates the Vite configuration file, installs necessary dependencies, updates package.json scripts, and sets up the new build structure. ```bash rails islandjs:init ``` -------------------------------- ### Package Management (Ruby API) Source: https://context7.com/praxis-emergent/islandjs-rails/llms.txt Manage installed JavaScript packages programmatically using the IslandjsRails Ruby API. This allows for dynamic control over dependencies within your Rails application. ```APIDOC ## Package Management (Ruby API) Programmatically manage packages from Ruby code. ```ruby # Install a package IslandjsRails.install!('react', '19.1.0') # Update package to new version IslandjsRails.update!('react', '19.1.0') # Remove package IslandjsRails.remove!('lodash') # Sync all packages from package.json IslandjsRails.sync! # Check if package is installed if IslandjsRails.package_installed?('react') version = IslandjsRails.version_for('react') puts "React #{version} is installed" end # Get global name for a library global_name = IslandjsRails.detect_global_name('@solana/web3.js') # => "solanaWeb3" # Clean all vendor files and rebuild IslandjsRails.clean! ``` ``` -------------------------------- ### IslandJS Rails Package Management (Bash) Source: https://github.com/praxis-emergent/islandjs-rails/blob/main/README.md These bash commands are used to manage JavaScript packages within an IslandJS Rails project. They cover initialization, installation, updating, removal, and cleaning of UMD files, interacting with the `package.json` and vendor directories. ```bash # Initialize IslandJS Rails rails islandjs:init # Install packages rails "islandjs:install[react]" rails "islandjs:install[react,19.1.0]" # With specific version rails "islandjs:install[lodash]" # Update packages rails "islandjs:update[react]" rails "islandjs:update[react,19.1.0]" # To specific version # Remove packages rails "islandjs:remove[react]" rails "islandjs:remove[lodash]" # Clean all UMD files rails islandjs:clean # Show configuration rails islandjs:config ``` -------------------------------- ### React Component with Turbo Cache Integration Source: https://github.com/praxis-emergent/islandjs-rails/blob/main/README.md An example of a React component written in JSX that utilizes `useTurboProps` to access initial props and `useTurboCache` for state persistence across Turbo navigations. It demonstrates how to manage component state and ensure it survives page transitions. ```jsx //jsx/components/DashboardApp.jsx import React, { useState, useEffect } from 'react'; import { useTurboProps, useTurboCache } from '../utils/turbo.js'; function DashboardApp({ containerId }) { // Read initial state from data-initial-state attribute const initialProps = useTurboProps(containerId); const [userId] = useState(initialProps.userId); const [welcomeCount, setWelcomeCount] = useState(initialProps.welcomeCount || 0); // Setup turbo cache persistence for state across navigation useEffect(() => { const cleanup = useTurboCache(containerId, { userId, welcomeCount }, true); return cleanup; }, [containerId, userId, welcomeCount]); return (

Welcome user {userId}!

You've visited this dashboard {welcomeCount} times

); } export default DashboardApp; ``` -------------------------------- ### Rebuild Island.js Vendor Bundle Source: https://context7.com/praxis-emergent/islandjs-rails/llms.txt This bash command rebuilds the combined vendor bundle for Island.js, including a content hash for cache busting. It also shows an example of the output, indicating the creation of a new bundle and the removal of an old one. ```bash # Rebuild combined vendor bundle with content hash rails islandjs:vendor:rebuild_combined # Output: # Combined bundle created: islands-vendor-a1b2c3d4e5f6.js (142.5 KB) # Removed old bundle: islands-vendor-f6e5d4c3b2a1.js ``` -------------------------------- ### Usage of Turbo-Compatible React Component in ERB Source: https://github.com/praxis-emergent/islandjs-rails/blob/main/README.md Shows how to render a Turbo-compatible React component within a Rails view using the `react_component` helper. This setup automatically handles the data attributes required for state persistence and restoration across Turbo navigation. ```erb <%= react_component('HelloWorld', { message: 'Hello from Rails!', count: 5 }) %> ``` -------------------------------- ### Check Island.js Vendor System Status Source: https://context7.com/praxis-emergent/islandjs-rails/llms.txt This bash command allows you to check the current status of the Island.js vendor system. It displays the mode, vendor directory, and a list of installed packages with their versions and corresponding filenames. ```bash # Check vendor system status rails islandjs:vendor:status # Output: # Mode: external_split # Vendor directory: /home/app/public/vendor/islands # # Installed packages: # react (19.1.0) - react-19.1.0.min.js # react-dom (19.1.0) - react_dom-19.1.0.min.js # lodash (4.17.21) - lodash-4.17.21.min.js # # Partial: app/views/shared/islands/_vendor_umd.html.erb ``` -------------------------------- ### React Component Using Global Scope Source: https://github.com/praxis-emergent/islandjs-rails/blob/main/README.md Shows a React component that utilizes a globally available JavaScript variable, `solanaWeb3`, which is automatically provided by IslandJS Rails for installed scoped packages. This component demonstrates creating a Solana connection using the global object. ```jsx // jsx/components/SolanaComponent.jsx import React from 'react'; function SolanaComponent() { // solanaWeb3 is automatically available as a global variable on the window object const connection = new window.solanaWeb3.Connection('https://api.devnet.solana.com'); return (

Solana Integration

Connected to: {connection.rpcEndpoint}

); } export default SolanaComponent; ``` -------------------------------- ### Turbo-Compatible React Component (JSX) Source: https://github.com/praxis-emergent/islandjs-rails/blob/main/README.md A React component designed for IslandJS Rails that utilizes `useTurboProps` to read initial state and `useTurboCache` to persist state across Turbo navigation. This example shows how to manage component state that should survive page transitions. ```jsx import React, { useState, useEffect } from 'react'; import { useTurboProps, useTurboCache } from '../utils/turbo.js'; const HelloWorld = ({ containerId }) => { // Read initial state from data-initial-state attribute const initialProps = useTurboProps(containerId); const [count, setCount] = useState(initialProps.count || 0); const [message, setMessage] = useState(initialProps.message || "Hello!"); // ensures persists state across Turbo navigation useEffect(() => { const cleanup = useTurboCache(containerId, { count, message }, true); return cleanup; }, [containerId, count, message]); return (

{message}

); }; ``` -------------------------------- ### Automatic Global Name Conversion Source: https://github.com/praxis-emergent/islandjs-rails/blob/main/README.md Illustrates how IslandJS Rails automatically transforms scoped JavaScript package names into valid JavaScript global names. The example shows the conversion of '@solana/web3.js' to 'solanaWeb3' by removing the scope and applying camelCase. ```ruby # Automatic conversions: '@solana/web3.js' => 'solanaWeb3' # Scope removed, camelCase ``` -------------------------------- ### Access UMD JS Packages in React Components (Bash) Source: https://github.com/praxis-emergent/islandjs-rails/blob/main/README.md This snippet demonstrates how to access UMD-installed JavaScript packages, such as Quill, from within React components by using the global `window` object. It's crucial for libraries that provide UMD builds and assumes the package has been correctly installed and made available globally. ```bash # in SomeComponent.jsx const quill = new window.Quill("#editor", { theme: "snow", }); ``` -------------------------------- ### Implement Error Handling in Island.js React Component for Rails Source: https://context7.com/praxis-emergent/islandjs-rails/llms.txt Provides a React component example for Island.js that includes robust error handling and a fallback UI. It uses `useState` and `useEffect` to manage data fetching, loading states, and error messages, displaying a retry button when an error occurs. ```jsx // app/javascript/islands/components/DataTable.jsx import React, { useState, useEffect } from 'react'; import { useTurboProps } from '../utils/turbo.js'; function DataTable({ containerId }) { const initialProps = useTurboProps(containerId); const [data, setData] = useState(initialProps.data || []); const [error, setError] = useState(null); const [loading, setLoading] = useState(false); const fetchData = async () => { setLoading(true); setError(null); try { const response = await fetch(initialProps.apiEndpoint); if (!response.ok) throw new Error('Failed to fetch data'); const json = await response.json(); setData(json.data); } catch (err) { setError(err.message); console.error('DataTable error:', err); } finally { setLoading(false); } }; if (error) { return (

Failed to load data: {error}

); } if (loading) { return
Loading...
; } return ( {data.map(row => ( ))}
ID Name Status
{row.id} {row.name} {row.status}
); } export default DataTable; ``` ```erb <%= react_component('DataTable', { apiEndpoint: api_v1_users_path, data: @initial_users }) do %>
<% end %> ``` -------------------------------- ### IslandJS Rails Configuration Options Source: https://github.com/praxis-emergent/islandjs-rails/blob/main/README.md Details the configuration options available for IslandJS Rails within an initializer file (`config/initializers/islandjs.rb`). It covers settings for partials directory, vendor script delivery modes (split or combined), vendor directory, combined bundle filename, and library loading order. ```ruby # config/initializers/islandjs.rb IslandjsRails.configure do |config| # Directory for ERB partials (default: app/views/shared/islands) config.partials_dir = Rails.root.join('app/views/shared/islands') # Vite Islands configuration is at vite.config.islands.ts (auto-managed) # Vendor file delivery mode (default: :external_split) config.vendor_script_mode = :external_split # One file per library # config.vendor_script_mode = :external_combined # Single combined bundle # Vendor files directory (default: public/vendor/islands) config.vendor_dir = Rails.root.join('public/vendor/islands') # Combined bundle filename base (default: 'islands-vendor') config.combined_basename = 'islands-vendor' # Library loading order for combined bundles config.vendor_order = ['react', 'react-dom', 'lodash'] end ``` -------------------------------- ### Configure IslandJS Rails in Initializers Source: https://context7.com/praxis-emergent/islandjs-rails/llms.txt Configure IslandJS Rails behavior by setting options such as partials directory, vendor script mode, vendor directory, and supported CDNs within the `config/initializers/islandjs.rb` file. ```ruby # config/initializers/islandjs.rb IslandjsRails.configure do |config| # Directory for ERB partials containing vendor scripts config.partials_dir = Rails.root.join('app/views/shared/islands') # Vendor script delivery mode # :external_split - Each library as separate file (better caching) # :external_combined - All libraries in single bundle (fewer requests) config.vendor_script_mode = :external_split # Directory where UMD files are stored config.vendor_dir = Rails.root.join('public/vendor/islands') # Base name for combined vendor bundle config.combined_basename = 'islands-vendor' # Library loading order for combined bundles config.vendor_order = ['react', 'react-dom', 'lodash'] # Supported CDN sources for UMD downloads config.supported_cdns = [ 'https://unpkg.com', 'https://cdn.jsdelivr.net/npm' ] end ``` -------------------------------- ### Configure IslandJS Rails in Rails Application Source: https://github.com/praxis-emergent/islandjs-rails/blob/main/README.md Illustrates the configuration options available for IslandJS Rails within a Rails application using `IslandjsRails.configure`. It covers settings for partials directory, package.json path, vendor script delivery mode (split or combined), vendor directory, combined bundle filename, and library loading order. It also mentions that built-in global name mappings are automatically applied. ```ruby IslandjsRails.configure do |config| # Directory for ERB partials (default: app/views/shared/islands) config.partials_dir = Rails.root.join('app/views/shared/islands') # Vite Islands config is at vite.config.islands.ts (auto-managed) # Path to package.json (default: package.json) config.package_json_path = Rails.root.join('package.json') # Vendor file delivery mode (default: :external_split) config.vendor_script_mode = :external_split # One file per library # config.vendor_script_mode = :external_combined # Single combined bundle # Vendor files directory (default: public/vendor/islands) config.vendor_dir = Rails.root.join('public/vendor/islands') # Combined bundle filename base (default: 'islands-vendor') config.combined_basename = 'islands-vendor' # Library loading order for combined bundles config.vendor_order = ['react', 'react-dom', 'lodash'] # Built-in global name mappings are automatically applied # No custom configuration needed for common libraries end ``` -------------------------------- ### Package.json Scripts for Vite Builds Source: https://context7.com/praxis-emergent/islandjs-rails/llms.txt This `package.json` snippet defines scripts for managing Vite builds, including standard builds, dedicated builds for islands using a specific configuration file, and development servers with watch capabilities. ```json { "scripts": { "build": "vite build", "build:islands": "vite build --config vite.config.islands.ts", "dev": "vite", "dev:islands": "vite build --config vite.config.islands.ts --watch" } } ``` -------------------------------- ### Include All Vendor Scripts and Vite Bundle Source: https://github.com/praxis-emergent/islandjs-rails/blob/main/README.md Demonstrates the usage of the `islands` helper in an ERB template to include all necessary UMD vendor scripts and the main Vite bundle. This helper simplifies the process of loading client-side assets. ```erb <%= islands %> ``` -------------------------------- ### NPM/Yarn Scripts for Island.js Builds Source: https://context7.com/praxis-emergent/islandjs-rails/llms.txt These npm and yarn scripts facilitate the building and watching of Island.js bundles. They leverage Vite with specific configuration files for both production builds and development watch modes. ```bash # Build islands bundle npm run build:islands # or yarn build:islands # Watch mode for development npm run watch:islands ``` -------------------------------- ### Vite Configuration for Island.js Builds Source: https://context7.com/praxis-emergent/islandjs-rails/llms.txt This TypeScript configuration file sets up Vite for building Island.js applications. It specifies entry points, library output formats, external dependencies, global mappings, and output directories, along with options for sourcemaps and manifest generation for Rails asset fingerprinting. ```typescript // vite.config.islands.ts import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' import path from 'path' export default defineConfig({ plugins: [react()], publicDir: false, build: { lib: { entry: path.resolve(__dirname, 'app/javascript/entrypoints/islands.js'), name: 'islandjsRails', formats: ['iife'], fileName: 'islands_bundle' }, rollupOptions: { // Externalize dependencies loaded via UMD external: ['react', 'react-dom', 'lodash'], output: { globals: { 'react': 'React', 'react-dom': 'ReactDOM', 'lodash': '_' }, entryFileNames: 'islands_bundle.[hash].js', chunkFileNames: 'chunks/[name].[hash].js' } }, outDir: 'public/islands', emptyOutDir: true, manifest: true, // Required for Rails asset fingerprinting sourcemap: process.env.NODE_ENV !== 'production' } }) ``` -------------------------------- ### IslandJS Rails Vendor System Management (Bash) Source: https://github.com/praxis-emergent/islandjs-rails/blob/main/README.md This section outlines bash commands for managing the IslandJS Rails vendor system, which handles the serving of UMD builds. It includes tasks for rebuilding combined vendor bundles and checking the status of the vendor system, supporting different modes like `:external_split` and `:external_combined`. ```bash # Rebuild the combined vendor bundle rails islandjs:vendor:rebuild # Show vendor system status and file sizes rails islandjs:vendor:status ``` -------------------------------- ### Render React Components in ERB Views Source: https://github.com/praxis-emergent/islandjs-rails/blob/main/README.md Shows how to render React components within ERB templates using the `react_component` helper provided by IslandJS Rails. It demonstrates basic rendering and how to include a placeholder for improved user experience during loading, especially with Turbo Stream partials. ```erb <%= react_component('DashboardApp', { userId: current_user.id }) %> <%= react_component('DashboardApp', { userId: current_user.id }) do %>
Loading dashboard...
<% end %> ``` -------------------------------- ### Module Configuration Source: https://context7.com/praxis-emergent/islandjs-rails/llms.txt Configure the behavior of IslandJS Rails within your Rails application by using the `configure` block in an initializer file. ```APIDOC ## Module Configuration Configure IslandJS Rails behavior through the configuration block. ```ruby # config/initializers/islandjs.rb IslandjsRails.configure do |config| # Directory for ERB partials containing vendor scripts config.partials_dir = Rails.root.join('app/views/shared/islands') # Vendor script delivery mode # :external_split - Each library as separate file (better caching) # :external_combined - All libraries in single bundle (fewer requests) config.vendor_script_mode = :external_split # Directory where UMD files are stored config.vendor_dir = Rails.root.join('public/vendor/islands') # Base name for combined vendor bundle config.combined_basename = 'islands-vendor' # Library loading order for combined bundles config.vendor_order = ['react', 'react-dom', 'lodash'] # Supported CDN sources for UMD downloads config.supported_cdns = [ 'https://unpkg.com', 'https://cdn.jsdelivr.net/npm' ] end ``` ``` -------------------------------- ### IslandJS Rails Development and Production Commands (Bash) Source: https://github.com/praxis-emergent/islandjs-rails/blob/main/README.md These bash commands facilitate the development and production build process for JavaScript assets managed by IslandJS Rails. They include commands for watching files during development and creating optimized production builds with content hashing. ```bash # Development - watch for changes and rebuild automatically yarn watch:islands # Production - build optimized bundle for deployment yarn build:islands # Install dependencies (after adding packages via islandjs:install) yarn install ``` -------------------------------- ### UMD Discovery and Download with Island.js Source: https://context7.com/praxis-emergent/islandjs-rails/llms.txt This Ruby code demonstrates how to programmatically discover, check accessibility, and download Universal Module Definition (UMD) builds for JavaScript packages from Content Delivery Networks (CDNs). It also shows how to detect the global variable name associated with a UMD module. ```ruby # Manual UMD discovery core = IslandjsRails::Core.new # Find working UMD URL for a package url = core.find_working_island_url('lodash', '4.17.21') # => "https://unpkg.com/lodash@4.17.21/lodash.min.js" # Check if URL is accessible accessible = core.url_accessible?(url) # => true # Download UMD content content = core.download_umd_content(url) # => "!function(){..." # Detect global name global_name = core.detect_global_name('lodash') # => "_" global_name = core.detect_global_name('@solana/web3.js') # => "solanaWeb3" ``` -------------------------------- ### IslandJS Rails Turbo Utility Functions (JavaScript) Source: https://github.com/praxis-emergent/islandjs-rails/blob/main/README.md Provides an overview of the core JavaScript utility functions offered by IslandJS Rails for seamless Turbo integration. These functions abstract the complexity of managing initial state and persisting component state across navigation. ```javascript // Get initial state from container's data attribute const initialProps = useTurboProps(containerId); // Set up automatic state persistence const cleanup = useTurboCache(containerId, currentState, autoRestore); // Manually persist state (if needed) persistState(containerId, stateObject); ``` -------------------------------- ### Update Build and Watch Scripts Source: https://github.com/praxis-emergent/islandjs-rails/blob/main/UPGRADING.md Adjust your package.json scripts to use the new build and watch commands specific to Vite integration. This ensures that your project is built and watched using the new Vite system. ```bash # Update 'yarn build' to 'yarn build:islands' # Update 'yarn watch' to 'yarn watch:islands' ``` -------------------------------- ### Create a Turbo-Compatible Shopping Cart Component Source: https://context7.com/praxis-emergent/islandjs-rails/llms.txt This React component, `ShoppingCart`, is designed to work with Island.js and Turbo. It demonstrates state persistence across Turbo navigation using `useTurboCache` and reads initial state from `data-initial-state` attributes via `useTurboProps`. ```jsx // app/javascript/islands/components/ShoppingCart.jsx import React, { useState, useEffect } from 'react'; import { useTurboProps, useTurboCache } from '../utils/turbo.js'; function ShoppingCart({ containerId }) { // Read initial state from data-initial-state attribute const initialProps = useTurboProps(containerId); const [items, setItems] = useState(initialProps.items || []); const [total, setTotal] = useState(initialProps.total || 0); // Recalculate total when items change useEffect(() => { const newTotal = items.reduce((sum, item) => sum + item.price, 0); setTotal(newTotal); }, [items]); // Persist state across Turbo navigation useEffect(() => { const cleanup = useTurboCache(containerId, { items, total }, true); return cleanup; }, [containerId, items, total]); const addItem = (item) => { setItems([...items, item]); }; const removeItem = (index) => { setItems(items.filter((_, i) => i !== index)); }; return (

Cart ({items.length} items)

Total: ${total.toFixed(2)}

); } export default ShoppingCart; ``` -------------------------------- ### React Component Helper Source: https://context7.com/praxis-emergent/islandjs-rails/llms.txt Render React components within ERB templates using the `react_component` helper. This helper handles automatic mounting, prop passing, and Turbo/Hotwire compatibility. ```APIDOC ## React Component Helper Render React components in ERB templates with automatic mounting and Turbo compatibility. ```erb <%# app/views/posts/show.html.erb %> <%# Basic usage %> <%= react_component('Counter') %> <%# With props %> <%= react_component('UserProfile', { userId: current_user.id, name: current_user.name, avatarUrl: current_user.avatar_url }) %> <%# With options %> <%= react_component('Dashboard', { data: @dashboard_data }, { container_id: 'custom-dashboard-id', tag: 'section', class: 'dashboard-container', nonce: content_security_policy_nonce, defer: true }) %> <%# With placeholder block for Turbo compatibility %> <%= react_component('Reactions', { postId: @post.id }) do %>
👍 ❤️ 🎉
<% end %> <%# With CSS placeholder %> <%= react_component('LoadingWidget', {}, { placeholder_class: 'widget-skeleton', placeholder_style: 'height: 120px; background: #f0f0f0;' }) %> ``` ``` -------------------------------- ### Turbo Stream Replace with React Placeholder Source: https://github.com/praxis-emergent/islandjs-rails/blob/main/README.md Demonstrates using `turbo_stream.replace` to update a section of a page with a React component that includes a placeholder. This pattern is ideal for dynamic content updates via Turbo Streams, ensuring a smooth user experience by minimizing content shifts. ```erb <%= turbo_stream.replace "post_#{@post.id}_reactions" do %> <%= react_component("Reactions", { postId: @post.id, reactions: @post.reactions.as_json }) do %>
Mounting/Rendering placeholder content goes here
<% end %> <% end %> ``` -------------------------------- ### Troubleshoot Vite Build Errors Source: https://github.com/praxis-emergent/islandjs-rails/blob/main/UPGRADING.md Provides solutions for common build failures encountered after migrating to Vite. This includes resolving ESM import issues, handling 'vite not found' errors, cleaning up old webpack files, and addressing manifest not found errors. ```bash # If build fails with "@vitejs/plugin-react resolved to an ESM file": # Add "type": "module" to your package.json. # If build fails with "vite not found": yarn install # If old webpack files are still present: rm webpack.config.js rm -rf node_modules/.cache/webpack # If manifest not found errors occur: yarn build:islands ``` -------------------------------- ### Register React Component Globally for Island.js Source: https://context7.com/praxis-emergent/islandjs-rails/llms.txt This JavaScript snippet demonstrates how to register a React component (like `Counter`) into the global `window.islandjsRails` object. This makes the component accessible to the Island.js runtime in your Rails application. ```javascript // app/javascript/entrypoints/islands.js import Counter from '../islands/components/Counter.jsx' // Register component in global namespace window.islandjsRails = { Counter } ``` -------------------------------- ### Vite External Configuration for Scoped Packages Source: https://github.com/praxis-emergent/islandjs-rails/blob/main/README.md Presents an auto-generated Vite configuration file (`vite.config.islands.ts`) that sets up externals for scoped packages. It specifies which packages should be treated as external dependencies and maps them to their corresponding global variables for UMD builds. ```typescript // vite.config.islands.ts (auto-generated) export default defineConfig({ build: { rollupOptions: { external: ['@solana/web3.js'], output: { globals: { '@solana/web3.js': 'solanaWeb3' } } } } }); ``` -------------------------------- ### Vite Configuration for IslandJS Rails Externals Source: https://github.com/praxis-emergent/islandjs-rails/blob/main/README.md Shows the auto-generated Vite configuration file (`vite.config.islands.ts`) used by IslandJS Rails. It specifies external dependencies like 'react' and 'react-dom', and defines their corresponding global variable names for the build output. This ensures that these libraries are treated as externals during the Vite build process. ```typescript export default defineConfig({ build: { rollupOptions: { external: ['react', 'react-dom'], output: { globals: { 'react': 'React', 'react-dom': 'ReactDOM' } } } } }); ``` -------------------------------- ### Island.js Turbo Utility Functions Source: https://context7.com/praxis-emergent/islandjs-rails/llms.txt A collection of JavaScript utility functions for integrating React components with Turbo in Rails. `useTurboProps` reads initial state from `data-initial-state`, and `useTurboCache` persists component state for Turbo's caching mechanism. ```javascript // app/javascript/islands/utils/turbo.js /** * Read initial props from container's data-initial-state attribute */ export function useTurboProps(containerId) { const container = document.getElementById(containerId); if (!container) { console.warn(`IslandJS: Container ${containerId} not found`); return {}; } const initialStateJson = container.dataset.initialState; if (!initialStateJson) return {}; try { return JSON.parse(initialStateJson); } catch (e) { console.warn('IslandJS: Failed to parse initial state', e); return {}; } } /** * Persist component state to data-initial-state for Turbo cache */ export function useTurboCache(containerId, currentState, autoRestore = true) { const container = document.getElementById(containerId); if (!container) { return () => {}; } // Persist current state to the container's data attribute try { const stateJson = JSON.stringify(currentState); container.dataset.initialState = stateJson; } catch (e) { console.warn('IslandJS: Failed to serialize state', e); } // Cleanup function (for useEffect return) return () => {}; } ``` -------------------------------- ### Create Reaction for a Post in Rails Controller Source: https://context7.com/praxis-emergent/islandjs-rails/llms.txt Handles the creation of a new reaction associated with a specific post in a Rails application. It finds the post, creates a reaction with the current user and provided emoji, and then updates the reaction UI using Turbo Streams. ```ruby class ReactionsController < ApplicationController def create @post = Post.find(params[:post_id]) @reaction = @post.reactions.create!( user: current_user, emoji: params[:emoji] ) respond_to do |format| format.turbo_stream do render turbo_stream: turbo_stream.replace( "post_#{@post.id}_reactions", partial: "posts/reactions", locals: { post: @post } ) end end end end ``` -------------------------------- ### Define Custom Namespace for IslandJS Rails Source: https://github.com/praxis-emergent/islandjs-rails/blob/main/README.md Demonstrates how to create a custom JavaScript namespace for IslandJS Rails, mapping common libraries to specific global variables. This allows for organized access to React, UI components, utilities, and charting libraries within your components. It highlights the flexibility in naming conventions. ```javascript window.islandjsRails = { React: window.React, UI: window.MaterialUI, Utils: window._, Charts: window.Chart }; // Use in components const { React, UI, Utils } = window.islandjsRails; ``` -------------------------------- ### Troubleshooting Package Not Found on CDN Source: https://github.com/praxis-emergent/islandjs-rails/blob/main/README.md Provides guidance for when a JavaScript package might not be found on a CDN, suggesting checks on unpkg.com and considering alternative packages or requesting UMD support. This is a common issue when integrating third-party libraries. ```ruby # Some packages don't publish UMD builds # Check unpkg.com/package-name/ for available files # Consider using a different package or requesting UMD support ``` -------------------------------- ### Rebuild Islands with Vite Source: https://github.com/praxis-emergent/islandjs-rails/blob/main/UPGRADING.md This command triggers a full rebuild of your islands using the new Vite build system. It's essential after completing the upgrade steps to ensure your application is correctly built. ```bash yarn build:islands ``` -------------------------------- ### Remove Webpack Configuration and Dependencies Source: https://github.com/praxis-emergent/islandjs-rails/blob/main/UPGRADING.md These commands remove the old webpack configuration file and uninstall webpack-related dependencies from your project's package.json. This is a necessary step when migrating to Vite. ```bash # Remove webpack config rm webpack.config.js # Remove webpack dependencies from package.json yarn remove webpack webpack-cli webpack-manifest-plugin ``` -------------------------------- ### Update IslandJS Rails Gem Source: https://github.com/praxis-emergent/islandjs-rails/blob/main/UPGRADING.md This command updates the islandjs-rails gem to the latest version using Bundler. Ensure you are in your project's root directory. ```bash bundle update islandjs-rails ``` -------------------------------- ### ERB Placeholder for React Component Source: https://github.com/praxis-emergent/islandjs-rails/blob/main/README.md Renders a placeholder content within an ERB block while the React component is mounting. This is the most flexible method, allowing custom HTML content for the placeholder. It helps prevent layout shifts by reserving space. ```erb <%= react_component("Reactions", { postId: post.id }) do %>
👍
❤️
🚀
Loading...
<% end %> ``` -------------------------------- ### Enable Island.js Rails Debug Mode Source: https://context7.com/praxis-emergent/islandjs-rails/llms.txt Activates the Island.js debug overlay in Rails development environments by setting an environment variable. This overlay displays information about loaded UMD libraries, global names, and Island bundle status. ```bash # Enable debug mode export ISLANDJS_RAILS_SHOW_UMD_DEBUG=1 rails server # Visit any page with <%= islands %> helper # You'll see an overlay showing: # - All loaded UMD libraries and versions # - Global names and availability # - Islands bundle status # - Vendor mode (split/combined) ``` -------------------------------- ### Inline Style Placeholder for React Component Source: https://github.com/praxis-emergent/islandjs-rails/blob/main/README.md Uses inline styles directly on the placeholder for a React component. This is a quick and simple way to define the placeholder's appearance, useful for straightforward cases where a dedicated CSS class is not needed. It ensures a consistent height and background. ```erb <%= react_component("Reactions", { postId: post.id }, { placeholder_style: "height: 40px; background: #f8f9fa; border-radius: 4px;" }) %> ``` -------------------------------- ### Configure Content Security Policy for Island.js Rails Source: https://context7.com/praxis-emergent/islandjs-rails/llms.txt Configures Rails to generate CSP nonces for script sources, ensuring secure execution of dynamically loaded JavaScript, including React components used with Island.js. It sets default and script sources, with specific rules for development and production environments. ```ruby # config/initializers/content_security_policy.rb Rails.application.configure do config.content_security_policy do |policy| policy.default_src :self policy.script_src :self, :unsafe_inline if Rails.env.development? policy.script_src :self if Rails.env.production? end config.content_security_policy_nonce_generator = ->(request) { SecureRandom.base64(16) } end ``` ```erb <%# The react_component helper automatically detects and uses CSP nonce %> <%= react_component('SecureComponent', { data: @data }) %> <%# Generated HTML includes nonce attribute: %> <%# %> ``` -------------------------------- ### Rendering React Component with Rails Helper Source: https://context7.com/praxis-emergent/islandjs-rails/llms.txt This ERB snippet demonstrates how to render a React component named 'SalesChart' within a Rails view using the `react_component` helper. This is a standard way to integrate React components into Rails applications managed by Island.js. ```erb <%= react_component('SalesChart') %> ``` -------------------------------- ### Configure Island.js for Combined Mode Source: https://context7.com/praxis-emergent/islandjs-rails/llms.txt Configure Island.js to use external combined vendor scripts and define the order of script inclusion. This is useful for managing third-party JavaScript dependencies. ```ruby IslandjsRails.configure do |config| config.vendor_script_mode = :external_combined config.vendor_order = ['react', 'react-dom', 'lodash'] end ``` -------------------------------- ### Set Custom Component Namespace for Island.js Rails Source: https://context7.com/praxis-emergent/islandjs-rails/llms.txt Demonstrates how to define a custom global namespace for Island.js components instead of the default 'window.islandjsRails'. This is useful for organizing components and avoiding global scope conflicts. ```javascript // app/javascript/entrypoints/islands.js window.MyApp = window.MyApp || {}; window.MyApp.components = { Counter: Counter, Dashboard: Dashboard }; ``` ```erb <%= react_component('Counter', {}, { namespace: 'window.MyApp.components' }) %> ```