最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Imported Javascript function not defined when called from html - Stack Overflow

programmeradmin10浏览0评论

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.

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.

Share Improve this question asked Dec 27, 2017 at 14:17 DisturbDisturb 5988 silver badges15 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 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 remend 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.

发布评论

评论列表(0)

  1. 暂无评论