简体   繁体   中英

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.

https://jsfiddle.net/danwillm/bkgtnm6s/

Is there any way to do this?

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 .

Your script works in a SO snippet, as you can see below

 function foo(test){ console.log(test); }
 <a onClick="foo('bar');" class="blue left desktop-only pointer">click here</a>

It did not work in jsfiddle probably because of scope issues: The script is probably executed in its own scope and a function definition there was not reachable by the onclick in the HTML. I modified your function definition so it would always land in the global scope

foo=function(test){console.log(test);}

and now it works there too, see here: https://jsfiddle.net/obuvjn0m/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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