webpack 包不让 html 识别我的 js 函数
2020-05-24
415
我的 HTML 抽屉中有一个函数,当页面加载时,它会自动点击第一个选项卡。当我使用 webpack 捆绑 JS 时,html 给出了一个
Uncaught ReferenceError: openTab is not defined
,这不允许我的 openTab 函数在页面加载时工作。正常的 controller.js 可以正常工作。
webpack.config.js
const path = require('path');
module.exports = {
entry: {
app: './src/js/controller.js'
},
output: {
path: path.resolve(__dirname, 'dist/build'),
filename: 'controller.bundle.js'
},
module : {
rules: [{
// A regex that looks at all Javascript files
test: /\.js?$/,
exclude : /node_modules/,
loader: 'babel-loader',
//this is where we define our presets
query: {
presets:['@babel/preset-env']
}
}]
}
}
package.json
"main": "controller.js",
"scripts": {
"dev": "webpack --mode development",
"build": "webpack --mode production",
"start": "webpack-dev-server --mode development --open"
},
"devDependencies": {
"@babel/core": "^7.9.6",
"@babel/preset-env": "^7.9.6",
"babel-loader": "^8.1.0",
"html-webpack-plugin": "^4.3.0",
"webpack": "^4.43.0",
"webpack-cli": "^3.3.11",
"webpack-dev-server": "^3.11.0"
},
"dependencies": {
"axios": "^0.19.2",
"core-js": "^3.6.5",
"express": "^4.17.1",
"regenerator-runtime": "^0.13.5"
}
}
home.html //最后一个 div 之后的内容是每个选项卡内容所在的位置。当该函数不运行时,所有内容都是可见的。
<div class="drawer__content">
<div class="tab">
<button class="tablinks " onclick="openTab(event, 'Home')" id="defaultOpen"><i class="fas fa-home"></i></button>
<button class="tablinks" onclick="openTab(event, 'Fav')"><i class="fas fa-star"></i></button>
<button class="tablinks" onclick="openTab(event, 'Settings')"><i class="fas fa-cogs"></i></button>
</div>
controller.js
function openTab(evt, tabName) {
// Declare all variables
var i, tabcontent, tablinks;
// Get all elements with class="tabcontent" and hide them
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
// Get all elements with class="tablinks" and remove the class "active"
tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace(" active", "");
}
// Show the current tab, and add an "active" class to the link that opened the tab
document.getElementById(tabName).style.display = "block";
evt.currentTarget.className += " active";
}
document.getElementById("defaultOpen").click()
2个回答
我发现了一篇旧帖子,有人遇到了同样的问题。我认为这与将函数设为全局函数有关。
我需要做的是将 html 中的
onclick
函数从
function openTab()
更改为
openTab = function()
这样就解决了所有问题。
SkepticalTiger
2020-05-25
使用
addEventListener
可能会有所帮助,而不是将
onclick="openTab(event, 'Home')"
直接放入 HTML 中的按钮中。
例如,对于带有
id="defaultOpen"
的按钮,请尝试使用下一个:
const button1 = document.getElementById("defaultOpen");
button1.addEventListener("click", function () {
openTab(event, 'Home')
});
Nataly Chkhan
2023-01-23