0

Recently I am learning to use rails7, but when I use importmap to refer to my js file, I always get an error: [ testalert is not defined ], please help me

testjs.js is my js file

app/javascript/testjs.js

.....
  function testalert(){
    alert('call from testjs');
  }

app/views/welcome/index.html.erb

......
<input type='button' onclick="testalert();" value='test alert'>

importmap.rb

pin "application", preload: true
pin "@hotwired/turbo-rails", to: "turbo.min.js", preload: true
pin "@hotwired/stimulus", to: "stimulus.min.js", preload: true
pin "@hotwired/stimulus-loading", to: "stimulus-loading.js", preload: true
pin_all_from "app/javascript/controllers", under: "controllers"
pin "testjs", preload: true

application.js

import "@hotwired/turbo-rails"
import "controllers"
import "testjs"

app/assets/config/manifest.js

//= link_tree ../images
//= link_directory ../stylesheets .css
//= link_tree ../../javascript .js
//= link_tree ../../../vendor/javascript .js

config/initializers/assets.rb

 ......
 Rails.application.config.assets.precompile += %w( testjs.js )

when i click the web page button [test alert] should pop up a alert windows ,but always get the error message enter image description here

the html head enter image description here

Does anyone know why and how to fix it , Thank you

System configuration Rails version: rails 7.0.5 Ruby version: ruby 3.1.2

I have followed https://stackoverflow.com/questions/70548841/how-to-add-custom-js-file-to-new-rails-7-project/72855705#72855705 but the error still occurs

0 Answers0