Performance: Webpacker and JavaScript bundling
This affects how quickly JavaScript files load and execute, impacting page load speed and interactivity.
use Webpacker's code splitting and dynamic imports to load JavaScript on demandimport all scripts in one large bundle without code splitting or lazy loading
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Single large bundle | Minimal DOM impact | 1 reflow after script execution | High paint cost due to delayed rendering | [X] Bad |
| Code splitting with lazy loading | Minimal DOM impact | 1 reflow after critical scripts | Lower paint cost, faster rendering | [OK] Good |
javascript_pack_tag to include JS bundles.<%= javascript_pack_tag 'pack_name' %>, so <%= javascript_pack_tag 'application' %> matches.app/javascript/packs/hello.js with content:import { greet } from '../utils/greet'
console.log(greet('Rails'))app/javascript/utils/greet.js contains:export function greet(name) {
return `Hello, ${name}!`
}greet function is exported from utils/greet.js and imported correctly in hello.js.greet('Rails') returns the string Hello, Rails!, which is logged.app/javascript/packs/custom.js but when you include it with <%= javascript_pack_tag 'custom' %>, the browser console shows a 404 error. What is the most likely cause?app/javascript/packs/, so location is likely correct.app/javascript/modules/calc.js exporting a function add(a, b). How should you import and use this function in your pack file app/javascript/packs/main.js to log the sum of 5 and 7?add is a named export, import it with curly braces: import { add } from 'path'.add(5, 7) and log the result with console.log.Pass the test and this pattern moves unknown