Kevin Chandra
Kevin Chandra

Reputation: 715

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. The code below works for the styling, but the handleClick is not working. Is this possbile?

This is my 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

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

this is my 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

div {
 background-color:blue;
}

Upvotes: 0

Views: 1069

Answers (2)

Shib
Shib

Reputation: 306

The better way is to add addEventListener to that element using your js file. 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.

Upvotes: 1

Bohdan Oliinyk
Bohdan Oliinyk

Reputation: 11

Suggest to check namespace of index.js - as i expect, webpack will wrap it in a namespace. Try to define function on a window namespace.

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

Upvotes: 0

Related Questions