Migrating to Vite

If you would like to add a note about Sprockets, pull requests are welcome!

Starting Fresh ☀️

When starting a new project, follow the guide, and you should have a basic setup where you can place your JavaScript, stylesheets, and other assets.

Webpacker 📦

When migrating from Webpacker, start by following the guide to get a basic setup working before proceeding to migrate existing code.

During installation, Vite Ruby detect if the app/javascript directory exists, and use that in your config/vite.json instead of the default.

{
  "all": {
    "sourceCodeDir": "app/javascript",
    ...

One entry at a time

The recommended approach for medium-to-large-sized applications is to migrate one entrypoint at a time if possible. Gradually move each file in app/javascript/packs (managed by Webpacker) to app/javascript/entrypoints (managed by Vite Ruby).

Check this migration from Webpacker as an example.

Proceed to fix any errors that occur (i.e. differences between Webpack and Vite.js) by checking the Troubleshooting section and the following recommendations:

  • Explicitly add a file extension to any non-JS imports.

    - import TextInput from '@/components/TextInput'
    + import TextInput from '@/components/TextInput.vue'
    
  • Replace usages of tag helpers as you move the entrypoints.

    + <%= vite_client_tag %>
    
    - <%= stylesheet_pack_tag 'application' %>
    - <%= javascript_packs_with_chunks_tag 'application' %>
    + <%= vite_javascript_tag 'application' %>
    
    - <%= stylesheet_pack_tag 'mobile' %>
    + <%= vite_stylesheet_tag 'mobile' %>
    
    - <img src="<%= asset_pack_path('images/logo.svg') %>">
    + <img src="<%= vite_asset_path('images/logo.svg') %>">
    
  • Replace require.context with import.meta.glob or import.meta.globEager.

    - const context = require.context("./controllers", true, /\.js$/)
    + const controllers = import.meta.globEager('./**/*_controller.js')
    
  • If importing code that is located outside of the sourceCodeDir, make sure to add a glob expression in watchAdditionalPaths, so that changes to these files are detected, and trigger a recompilation.

  • If you were using rails-erb-loader, you might want to check vite-plugin-erb to ease the transition, but it's better to avoid mixing ERB in frontend assets.

  • Make sure npx is available (comes by default in most node.js installations), or clear the vite:install_dependencies rake task and provide your own implementation.

Loaders to Plugins

Vite provides many features out of the box, which reduce the need for configuration.

In complex setups, the app might depend on specific webpack loaders, which can't be used in Vite, which uses Rollup under the hood.

Check Vite Rollup Plugins and Awesome Vite to find equivalent plugins.