javascript - 如何在html中使用webpack构建的js文件中声明的函数?

标签 javascript node.js webpack

所以,我想做的是,基于 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/

相关文章:

node.js - 使用 Node Express 提供静态文件时正确的脚本路径是什么?

node.js - npm 命令什么也不做 - Windows

reactjs - 从外部源动态加载 React 组件/包

reactjs - React + Webpack + ES6 中的动态组件名称

javascript - 使用 javascript 在表格单元格中插入数组值

c# - 如何在 C# 中获取另一个网站页面的 JavaScript 函数的结果?

javascript - if 语句中的 jQuery UI 对话框按钮

javascript - Ng 重复不在 li 内工作弹出窗口

python - Heroku 部署,Yuglify 使用 Django 管道没有这样的文件

javascript - 在 Next.js 项目中添加 webpack 插件