所以,我想做的是,基于 template.html
生成一个名为 index.html
的 html 文件,该文件的样式基于 style.css
和在 index.js
中声明的函数 handleClick
。下面的代码适用于样式,但 handleClick
不起作用。这可能吗?
这是我的webpack.config.js
const path = require('path')
const HTMLWebpackPlugin = require('html-webpack-plugin')
module.exports = {
entry: {
'page': './src/index.js'
},
output: {
path: path.join(__dirname, '/dist'),
filename: "[name].js"
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: [
'babel-loader'
]
},
{
test: /\.css$/,
use: [
"style-loader",
"css-loader"
]
}
]
},
plugins: [
new HTMLWebpackPlugin({
filename: 'index.html',
template: './src/template.html'
})
]
}
这是我的index.js
require('./style.css');
function handleClick(){
alert("called from index")
}
这是我的template.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>My Page's Title</title>
</head>
<body>
<div>This background should be blue</div>
<button onclick="handleClick()"> click me </button>
</body>
</html>
这是我的style.css
div {
background-color:blue;
}
最佳答案
更好的方法是使用 js 文件将 addEventListener
添加到该元素。你可以这样做:
<button id="buttonWithFunction"> click me </button>
<script>
// pure js
document.getElementById('buttonWithFunction').addEventListener('click', handleClick);
//with jquery loaded
$('#buttonWithFunction').on('click',function() {
handleClick();
})
您可能需要将以下内容包装在 document.onload 中才能正常工作。
关于javascript - 如何在html中使用webpack构建的js文件中声明的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58587016/