6

I set up a new Rails 7 project with esbuild: rails new my_project -j esbuild

I then added Vue.js with yarn add vue.

I can see that Vue was added successfully to my package.json file:

{
  "name": "app",
  "private": "true",
  "dependencies": {
    "@hotwired/stimulus": "^3.0.1",
    "@hotwired/turbo-rails": "^7.1.1",
    "autoprefixer": "^10.4.5",
    "esbuild": "^0.14.38",
    "postcss": "^8.4.13",
    "tailwindcss": "^3.0.24",
    "vue": "^3.2.33"
  },
  "scripts": {
    "build": "esbuild app/javascript/*.* --bundle --sourcemap --outdir=app/assets/builds",
    "build:css": "tailwindcss -i ./app/assets/stylesheets/application.tailwind.css -o ./app/assets/builds/application.css --minify"
  }
}

I then added import "./vue_controllers" to my application.js file:

// Entry point for the build script in your package.json
import "@hotwired/turbo-rails"
import "./controllers"
import "./vue_controllers"

and placed some basic Vue.js code in ./vue_controllers/test.js:

import Vue from 'vue';

document.addEventListener('turbo:load', () => {
  const element = document.getElementById('point');
  if (element != null) {
    const app = Vue.createApp({
      data() {
        return { count: 1 }
      },
      created() {
        alert(`count is: ${this.count}`)
      }
    })
    const vm = app.mount(element)
  }
})

When I start the server with ./bin/dev, I get the following error:

13:07:47 js.1   | ✘ [ERROR] Could not resolve "./vue_controllers"
13:07:47 js.1   |
13:07:47 js.1   |     app/javascript/application.js:4:7:
13:07:47 js.1   |       4 │ import "./vue_controllers"
13:07:47 js.1   |         ╵        ~~~~~~~~~~~~~~~~~~~
13:07:47 js.1   |
13:07:47 js.1   | 1 error

I then tried to place the file within ./controllers instead. I don't get an error when I do that but the js file doesn't get loaded.

I also tried renaming the file to ./controllers/test_controller.js but it still doesn't run.

The only way I can make this kind of run is by placing the code directly in my application.js file. When I do that, the Vue code is executed, the object it's mounted to gets rendered for a second and then disappears.

Any idea how I can run Vue.js code using Rails 7 and esbuild?

Thanks in advance

DaniG2k
  • 4,772
  • 36
  • 77

1 Answers1

0

I think that you're having that error because you're trying to import a folder instead of a file. So if you placed the component in ./vue_controllers/test.js, you should change the application.js file to:

// Entry point for the build script in your package.json
import "@hotwired/turbo-rails"
import "./controllers"
import "./vue_controllers/test"