Search code examples
javascripthtmlwebpackwebpack-4

HTML inline javascript with webpack


I am currently starting to use webpack for my website and I have a question.

I currently have a html page that includes my javascript bundle and has some onclick functions in buttons embedded in the html. I would like to keep the functionality of these buttons and the onclick, but currently I have not found a way to do this. Obviously, if I try to minify the javascript functions, the name of the function would change and it won't work.

Here's an example, where the bundle produced by webpack is included in the html file:

<button onclick="foo("bar")">test</button> and currently foo is undefined.

I have tried using html webpack plugin without success.

Is there any way to do this?


Solution

  • Yes you can get to the function but you will still have to modify the code slightly - onClick.

    webpack

    const path = require('path');
    const HtmlWebPackPlugin = require('html-webpack-plugin');
    const {
      CleanWebpackPlugin
    } = require('clean-webpack-plugin');
    
    module.exports = (env, argv) => {
      return {
        devtool: argv.mode === 'production' ? 'none' : 'source-map',
        mode: argv.mode === 'production' ? 'production' : 'development',
        entry: {
          MYSCRIPT: './sources/script.js'
        },
        output: {
          path: path.resolve(__dirname, './dist'),
          filename: './[name].js',
          library: '[name]',
          libraryTarget: 'var',
        },
        module: {
          rules: [{
            test: /\.js$/,
            exclude: /node_modules/,
            use: {
              loader: 'babel-loader'
            }
          }, ]
        },
        plugins: [
          new CleanWebpackPlugin({
            verbose: true
          }),
          new HtmlWebPackPlugin({
            filename: 'index.html',
            template: './sources/index.html'
          })
        ]
      }
    }
    

    The most important part is the name entry and outputs. You must also export each function.

    JS

    export function test(type) {
      alert(type);
    }
    

    And we can get to the function this way.

    HTML

    <a onClick="MYSCRIPT.test('bar')">click</a>
    

    You can find the whole devising example here.