Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How access JS function using Import Maps in Ruby On Rails 7?

I'm newbie to JS modules and Import Map, now I'm using Ruby on Rails 7 and I couldn't find a way to get this working:

Js Module (proposals.js):

function openProposalMirror() ...

application.js

import * as Proposal from "./proposals.js"

On the view:

onclick="Proposal.openProposalMirror()"

error: Uncaught ReferenceError: Proposal is not defined

How could I accesse openProposalMirror() function on the view?

like image 640
Gedean Dias Avatar asked Jun 19 '26 00:06

Gedean Dias


1 Answers

One way to go is to assign the Proposal to the object window.Proposal.

you could set directly inside the application.js as below:

// proposals.js
function openProposalMirror() {}
export { openProposalMirror }

// application.js
import * as Proposal from "./proposals.js"
window.Proposal = Proposal

// view
onclick="Proposal.openProposalMirror()"

you could also re-export Proposal from application.js then import and assign it to the object window.Proposal in a <script> tag (in view) as below:

// application.js
import * as Proposal from "./proposals.js"
export { Proposal };

// view
<%= javascript_importmap_tags %>

<script type="module">
  import { Proposal } from "application"
  window.Proposal = Proposal;
</script>
like image 133
Lam Phan Avatar answered Jun 21 '26 12:06

Lam Phan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!