4

I'm learning laravel 5.5 and VueJs, my issue is when I export some functions from a js file and import it from a second js file it cannot be called from html body. Example:

A.js

function funA(){
}
export {funA};

B.js

import {funA} from './A.js';

At this point if I use the function funA inside the B.js it works, however if I use it on a html page it says funA is not defined. For example:

<!DOCTYPE html>
<html lang="en">
<body>
  <button onClick="funA()"></button>
  <script src="{{asset('js/B.js')}}"></script>
</body>
</html>

My webpack configuration is something like this:

mix.scripts('resources/assets/js/libs/materialize.js', 'public/js/libs/materialize.js')
    .js('resources/assets/js/A.js', 'public/js/js/A.js')
    .js('resources/assets/js/B.js', 'public/js/B.js');

Any help would be appreciated. Thank you in advanced.

1 Answer 1

8

I think your HTML expects the funA to be on the global window object. The new JavaScript module system doesn't add anything to the global namespace, to avoid namespace pollution.

If you just want to use is anyways on the button then, doing the below should get you working.

window.funA = funA

You can do this in your B.js. Though, I will not recommend this, as I see that you seem to be using Vue and there are better ways to do it. Let me know if this works, also try sharing your Vue code so that someone can help you do it the right way.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you this really worked, I know with Vuejs there are other ways to do it, however the A.js contains a lot of helper functions that I use in the whole system, and I need it to be independent from VueJs. Again thank you.
You might try setting the functions on your root vue instance.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.