2

I have Rails 7.0.4.

I generated the project using this command.

rails new myproject --database=postgresql -j esbuild --css bootstrap

Thus, I don't have a file named config/importmap.rb.

How do I load a single file with custom JS?

I tried creating a file with a single console.log here.

// ./app/javascript/new.js

console.log('Hi')

and then load this file into the entry point application.js like this.

// ./app/javascript/application.js

import "./new.js"

But I don't see any console.log.

Thanks in advance~!

PrimeTimeTran
  • 1,807
  • 2
  • 17
  • 29

1 Answers1

0

You're using esbuild which means you have to compile/bundle your javascript. Rails gives a command to start the server and run esbuild:

bin/dev

This is somewhat glanced over in the readme, but it's there: https://github.com/rails/jsbundling-rails

This should work just fine:

// app/javascript/application.js

import "./new"
Alex
  • 16,409
  • 6
  • 40
  • 56
  • Thank you for responding. Even with a brand new rails project, `rails new jsexample -j esbuild` this doesn't work, the JS isn't loaded and I don't see a log to the screen. I did run the project using `bin/dev` as well. Interestingly, I do see my custom JS inside of `./app/assets/builds/new.js` though, it just doesn't execute/log in the dev tools. – PrimeTimeTran Dec 28 '22 at 12:27
  • 1
    @PrimeTimeTran did you make a new controller? default rails page doesn't load the layout from your views. `bin/rails g controller home index` then go to `/home/index`. you have to import `new.js` in `application.js` because thats what's in the layout `javascript_include_tag "application"`. – Alex Dec 28 '22 at 14:30
  • I did what you advised, created a new controller and page, and then checked there, as opposed to checking from the default home page. It worked, I saw the console.log in my chrome dev tools. I ended up trying generating another rails project again to repeat and test the behavior and it worked a second time. My original project still wouldn't load the files though. I ended up copying over all of these files to the new install and then `rails db:reset` to get the js loaded. Strange. ./app/controllers/* ./app/helpers/* ./app/models/* ./app/views/* ./app/db/* ./Gemfile – PrimeTimeTran Dec 28 '22 at 17:00