我有以下index.html文件:
<html>
<head>
</head>
<body>
num1:<input id="num1" type="number">
num2:<input id="num2" type="number">
<button type="button" onclick="myFunction()">compute</button>
answer:<input id="demoInput" type="text"> and answer: <p
id="demoHtml"></p>
</body>
<script src="index.js"></script>
index.js 所在位置
function myFunction() {
var x = document.getElementById("num1").value;
var y = document.getElementById("num2").value;
var ans = parseInt(x) + parseInt(y)
document.getElementById("demoInput").value = ans;
document.getElementById("demoHtml").innerHTML = ans;
}
上面的代码完美运行。使用 webpack/browserify 会带来以下困难。如果我打电话
browserify index.js > bundle.js
然后编辑index.html文件来读取
<script src="bundle.js"></script>
并运行index.html文件,开发者工具中的浏览器控制台在按下计算按钮时显示以下错误:
index.html:14 Uncaught ReferenceError: myFunction is not defined at
HTMLButtonElement.onclick (index.html:14)
Webpack 提出了同样的挑战。也许我错误地实现了 webpack 和 browserify?在线搜索几乎没有获得任何见解。
最佳答案
由于“myFunction”现在位于模块内,因此您必须以某种方式使其可见。
尝试使用global对象:
global.myFunction = function () {
// ...
}
然后它应该再次对 html 可见。
关于javascript - browserify/webpack 破解简单的 HTML 文件(函数未定义),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43816050/