vite_ruby icon indicating copy to clipboard operation
vite_ruby copied to clipboard

Import aliases in Rails tag helpers

Open Splines opened this issue 6 months ago • 1 comments

🎈 Scenario

Related to #564. I want to structure my Rails codebase component-wise and created an app/components/ folder. This folder contains subfolders like app/components/feature1/. My Vite sourceCodeDir stays app/frontend. To reflect this scenario, I've specified:

// extract of config/vite.json
"watchAdditionalPaths": [
  "app/components/**/*"
],
"additionalEntrypoints": [
  "app/components/**/*"
],

This allows me to do this:

<!-- app/components/feature1/index.html.erb -->
<%= vite_javascript_tag "/app/components/feature1/index" %>

where /app/components/feature1/index.js is a JavaScript file. This works as expected 🤗

🎈 Problem

However, I cannot use import aliases in Rails tag helpers. According to this tip:

In order to reference these files it's highly recommended to define your own import aliases: ~ see here

So, I specify:

// extract of vite.config.mts
resolve: {
    alias: {
      "@components": "/app/components",
    },
  },

However, doing the following results in a path that cannot be resolved by Vite:

<!-- app/components/feature1/index.html.erb -->

<!-- does not work -->
<%= vite_javascript_tag "@components/feature1/index" %>

<!-- works fine -->
<%= vite_javascript_tag "/app/components/feature1/index" %>

I've also tried variations like this one in your example repo:

// extract of vite.config.mts
resolve: {
    alias: {
      '@components/': `${resolve(__dirname, 'app/components')}/`,
    },
  },

But unfortunately without success. It would be great, if Rails tag helpers could support import aliases as well.

Splines avatar Aug 10 '25 13:08 Splines

Alternatively, relative asset names would be awesome too, as I could then do this in the described scenario:

<!-- app/components/feature1/index.html.erb -->
<%= vite_javascript_tag "./index" %>

<!-- app/components/feature1/index.js is a JavaScript file -->

Splines avatar Aug 10 '25 13:08 Splines