简体   繁体   中英

Named functions in a javascript file using Webpack 4

I just started using Webpack 4 in a project and am new to Webpack. Once Webpack 4 was implemented, I noticed that named functions kept erroring saying [functionName] is not defined.

I have looked quite extensively over the last few days and have tried multiple options with no success. I am hoping for someone to help me work through this in a more direct fashion way.

function openNav(obj) {
    ...do something
}
@foreach (object in list)
{
 ...create some HTML

}
const bundleFileName = 'bundle';
const dirName = 'wwwroot/dist';

module.exports = (env, argv) => {
    return {
        mode: argv.mode === "production" ? "production" : "development",
        entry: [
            './src/Index.js',
            './src/css/site.css',
            './src/js/app.js'
        ],

        output: {
            filename: bundleFileName + '.js',
            path: path.resolve(__dirname, dirName)
        },
        module: {
            rules: [
                {
                    test: /\.css$/,
                    use: [{ loader: 'style-loader' }, { loader: 'css-loader' }]
                }
            ]
        },
        plugins: [
            new webpack.ProvidePlugin({
                $: 'jquery',
                jQuery: 'jquery'
            }),
            new CleanWebpackPlugin(),
            new MiniCssExtractPlugin({
                filename: bundleFileName + '.css'
            })
        ]
    };
};

I expected the button in the razor file to send the object over to the named function so something can happen like it did previously before webpack

You've said you're trying to use openNav from an onclick attribute. The problem there is that openNav has to be a global to be used that way, but Webpack is a module bundler . Functions at the top level of modules aren't globals. (Which is a good thing.)

The solution is to not use onxyz -attribute-style event handlers. Instead, use modern event handling ( addEventListener , probably with at least some event delegation).

To ease your transition from the old way to the modern way, you can expose a function globally from within a module like this (on browsers):

window.openNav = openNav;

I strongly recommend only doing that temporarily to make it easier to transition to modern event handling.

thats because your webpack config isnt set to understand how to handle javascript files, add this to your rules key:

{
  test: /\.jsx?/,
  loader: 'babel-loader'
}

you will also need to install babel loader that is in a version compatible with your babel core, for v7^ you need to install @babel/core @babel/loader etc, otherwise, babel-loader etc

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