0

I have the following code in React:

<div>
  <a href="#" onClick={() => window.alert('Clicked!')}>Click me!</a>
</div>

It's simple like that, but the onClick doesn't fire.

When inspecting the element in the browser, I see this:

<a href="#">Click me!</a>

So it just looks like babel(?) or webpack(?) doesn't copy the onClick-method.

My .babelrc:

{
    "presets": [
        "@babel/preset-react",
        "@babel/preset-env"
    ],
    "plugins": [
        "@babel/plugin-syntax-dynamic-import",
        "@babel/plugin-proposal-class-properties"
    ]
}

My webpack.config.js:

const webpack = require('webpack');
const path = require('path');
const HtmlWebPackPlugin = require("html-webpack-plugin");
const CopyPlugin = require("copy-webpack-plugin");
const CompressionPlugin = require("compression-webpack-plugin");
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const ImageMinimizerPlugin = require('image-minimizer-webpack-plugin');

module.exports = {
    entry: path.resolve(__dirname, 'src/index.js'),
    output: {
        filename: 'bundle.js',
        path: path.join(__dirname, 'dist')
    },
    module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                exclude: /(node_modules|bower_components)/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: [
                            '@babel/preset-env',
                            '@babel/preset-react'
                        ]
                    }
                }
            },
            { test: /\.css$/, use: ['style-loader', 'css-loader?url=false'] },
            { test: /\?(png|jpe?g|svg|gif)?`$/, use: 'file-loader', type: 'asset' }
        ]
    },
    plugins: [
        new HtmlWebPackPlugin({
            template: path.resolve(__dirname, 'public/index.html'),
            filename: 'index.html'
        }),
        new CopyPlugin({
            patterns: [{
                from: path.resolve(__dirname, 'public/assets'),
                to: 'assets',
                noErrorOnMissing: true
            }]
        }),
        new webpack.DefinePlugin({
            'process.env.PUBLIC_URL': '"/"'
        }),
        new CompressionPlugin(),
        new BundleAnalyzerPlugin(),
        new ImageMinimizerPlugin({
            deleteOriginalAssets: false,
            filename: '[path][name].webp',
            minimizerOptions: {
                plugins: ['imagemin-webp'],
            },
        })
    ]
};

Do I need an extra module/plugin to copy stuff like onClick?

Edit: solution

In my index.html-template, I hardcoded the include for bundle.js, but webpack also adds this. By removing the bundle.js script tag in the index.html file, the problem is solved.

Sam Leurs
  • 1,592
  • 1
  • 19
  • 48

0 Answers0