3

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?

SRack
  • 11,495
  • 5
  • 47
  • 60
  • Possible duplicate of [how to load a Javascript file to rails html erb](https://stackoverflow.com/questions/18533969/how-to-load-a-javascript-file-to-rails-html-erb) – Anuj Khandelwal Jun 26 '19 at 07:36
  • This is similar to https://stackoverflow.com/questions/18533969/how-to-load-a-javascript-file-to-rails-html-erb Maybe that's what you need? – Anuj Khandelwal Jun 26 '19 at 07:36
  • Thanks @AnujKhandelwal - I'm not sure that's what I'm after though. I'm looking to just import a single function, rather than load an entire file into the DOM. – SRack Jun 26 '19 at 08:04
  • Oh, my apologies for marking this as a possible duplicate. Is there a way I can undo that? – Anuj Khandelwal Jun 26 '19 at 08:06
  • Not a problem @AnujKhandelwal - appreciate any attempt to help out :) Believe you can withdraw a vote through either the close or flag button under the question. – SRack Jun 26 '19 at 08:25

1 Answers1

1

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.

Hughes
  • 366
  • 4
  • 13