簡體   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 . 下面的代碼適用於樣式,但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 中才能正常工作。

建議檢查 index.js 的命名空間 - 正如我所料, webpack 會將其包裝在命名空間中。 嘗試在 window 命名空間上定義 function。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM