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

Viewed 1058

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?

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.

Related