Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to import JS function into a js.erb file?

Is it possible to import a JS function to be used in a js.erb file?

For example:

// hello_world.js
const helloWorld = () => console.log('hello world');
export default helloWorld;

And:

// our_file.js.erb
import helloWorld from 'path/to/hello_world.js';

helloWorld();

I've had a pop at it and can't get it firing, so presume the answer is no - will happily accept a one word answer if this is indeed the case.

If not, how does one go about getting this working? Thanks in advance for all help / constructive criticism / mockery.


Edit

I'm not sure the suggested duplicate is a duplicate of this - I'm specifically looking to import a function, not load an entire script into the DOM. Is this possible?

like image 641
SRack Avatar asked Oct 22 '25 09:10

SRack


1 Answers

By making the function available on the window you can call it inside your view or js.erb file.

// hello_world.js
const helloWorld = () => console.log('hello world');

window.helloWorld = helloWorld;
// our_file.js.erb
helloWorld();

I'm not sure if this is best practice but it's a workaround.

like image 62
Hughes Avatar answered Oct 25 '25 00:10

Hughes



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!