鍍金池/ 問答/HTML5  HTML/ webpack打包后,module模塊中的函數(shù)無法在html標簽的事件中調(diào)用?

webpack打包后,module模塊中的函數(shù)無法在html標簽的事件中調(diào)用?

折騰了好久,求大佬指點~~最近才開始接觸webpack以及ES6的module,可能理解的有問題吧。。。希望大佬來指點一下我這個菜鳥。
我的想法是在一個module中定義函數(shù),在HTML的<button>中用onclick事件調(diào)用這個函數(shù)。

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已經(jīng)成功導入進來了,但是在點擊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無論是直接調(diào)用base對象里的函數(shù),還是調(diào)用home.js里定義的函數(shù),都顯示未定義。。。究竟該怎么實現(xiàn)呢???

回答
編輯回答
冷咖啡

module中定義的函數(shù)不是全局的,改用事件監(jiān)聽

2018年4月11日 05:06
編輯回答
柚稚

在window 寫下一個全局函數(shù)
this.hanshu = function(){

return "hanshu!";

}
然后在你的html 標簽內(nèi)加上
onclick="hanshu()";
即可。

今天遇到同樣的問題,為了后端好綁,自己寫個函數(shù)讓他們調(diào)用去吧,我可不想閑著再命名了...哈哈哈

2018年3月25日 22:52