webpack打包后,module模块中的函数无法在html标签的事件中调用?

折腾了好久,求大佬指点~~最近才开始接触webpack以及ES6的module,可能理解的有问题吧。。。希望大佬来指点一下我这个菜鸟。
我的想法是在一个module中定义函数,在HTML的<button>中用onclick事件调用这个函数。

module模块代码:
-- base.js --

export default {    
    msg: 'Hello World!',

    objClick: function() {
        console.log('Obj.clickFunction');
        return 'Obj.clickFunction';
    }
}

webpack的entry文件:
-- home.js --

import base from './base.js';

function myFunction() {
    let objClickVal = base.objClick();
    console.log('objClickVal:', objClickVal);
    return ;
}

console.log('base.msg:', base.msg);
console.log('base.objClick:', base.objClick);

webpack配置:

module.exports = {
    entry: {
        home: './js/home.js',
    },
    output: {
        filename: '[name].bundle.js',
        path: __dirname + '/dist',
    }
}

home页面<body>部分:
-- home.html --

    <button onclick="myFunction()">ObjClick</button>
    <button onclick="base.objClick()">Base.ObjClick</button>
    <script type="text/javascript" src="../dist/home.bundle.js"></script>

npm运行webpack打包后,控制台显示:

base.msg: Hello World!         home.bundle.js:124
 
base.objClick: ƒ () {          home.bundle.js:126
        console.log('Obj.clickFunction');
        return 'Obj.clickFunction';
}

base.msg、base.objClick都显示出来了,证明module已经成功导入进来了,但是在点击button的时候显示:

Uncaught ReferenceError: myFunction is not defined
    at HTMLButtonElement.onclick (home.html:18)
onclick @ home.html:18

Uncaught ReferenceError: base is not defined
    at HTMLButtonElement.onclick (home.html:19)
onclick @ home.html:19

onclick无论是直接调用base对象里的函数,还是调用home.js里定义的函数,都显示未定义。。。究竟该怎么实现呢???

阅读 8.1k
2 个回答

module中定义的函数不是全局的,改用事件监听

在window 写下一个全局函数
this.hanshu = function(){

return "hanshu!";

}
然后在你的html 标签内加上
onclick="hanshu()";
即可。

今天遇到同样的问题,为了后端好绑,自己写个函数让他们调用去吧,我可不想闲着再命名了...哈哈哈

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题