简体   繁体   English

如何使用html中webpack构建的js文件中声明的function?

[英]How to use function declared in js file that built by webpack in html?

So, what I'm trying to do is, generate a html file called index.html based on template.html , that have styling based on style.css and a function handleClick that declared in index.js . So, what I'm trying to do is, generate a html file called index.html based on template.html , that have styling based on style.css and a function handleClick that declared in index.js . The code below works for the styling, but the handleClick is not working.下面的代码适用于样式,但handleClick不起作用。 Is this possbile?这可能吗?

This is my webpack.config.js这是我的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'
        })
    ]
}

this is my index.js这是我的index.js

require('./style.css');
function handleClick(){
    alert("called from index")
}

this is my template.html这是我的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>

and this is my style.css这是我的style.css

div {
 background-color:blue;
}

The better way is to add addEventListener to that element using your js file.更好的方法是使用您的 js 文件将addEventListener添加到该元素。 You can do it like this:你可以这样做:

<button id="buttonWithFunction"> click me </button>

<script>
// pure js
document.getElementById('buttonWithFunction').addEventListener('click', handleClick);

//with jquery loaded
$('#buttonWithFunction').on('click',function() {
     handleClick();
})

You may need to wrap the following in a document.onload for that to work.您可能需要将以下内容包装在 document.onload 中才能正常工作。

Suggest to check namespace of index.js - as i expect, webpack will wrap it in a namespace.建议检查 index.js 的命名空间 - 正如我所料, webpack 会将其包装在命名空间中。 Try to define function on a window namespace.尝试在 window 命名空间上定义 function。

window.handleClick = () => console.log('Clicked');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM