Home > Back-end >  Adding custom Js in WebPack and using it via MVC HTML helper
Adding custom Js in WebPack and using it via MVC HTML helper

Time:10-23

I am new to WebPack: I have an MVC 5 project using DotNet Core. My front end is all HTML and Razor with bootstrap for the css. I setup my webpackconfig.js and my site.js. All those work fine with NPM packages. When I try to add our own CDN or a local JS file I can't access the function I created. I'm posting the webpackconfig.js, the site.js, my custom.js and the html.

I am trying to add an onchange to my EditFor. I'm not getting any errors. I'm just not sure on how I'm suppose to call that JS function.

Webpackconfig.js

const path = require('path');

module.exports = {
    entry: {
        site: './src/js/site.js',
        event: './src/js/eventMessage.js'
    },
    output: {
        filename: '[name].entry.js',
        path: path.resolve(__dirname, 'wwwroot', 'dist')
    },
    devtool: 'source-map',
    mode: 'development',
    module: {
        rules: [
            {
                test: /\.(scss|css)$/,
                use: [
                    'style-loader',
                    'css-loader',
                    'sass-loader'
                ]
            },
            {
                test: /\.eot(\?v=\d \.\d \.\d )?$/,
                type: 'asset/resource',
            },
            {
                test: /\.(woff|woff2)$/, use: [
                    {
                        loader: 'url-loader',
                        options: {
                            limit: 5000,
                        },
                    },
                ]
            },
            {
                test: /\.ttf(\?v=\d \.\d \.\d )?$/, use: [
                    {
                        loader: 'url-loader',
                        options: {
                            limit: 10000,
                            mimetype: 'application/octet-stream',
                        },
                    },
                ]
            },
            {
                test: /\.svg(\?v=\d \.\d \.\d )?$/, use: [
                    {
                        loader: 'url-loader',
                        options: {
                            limit: 10000,
                            mimetype: 'image/svg xml',
                        },
                    },
                ]
            },
            {
                test: /\.(png|jpe?g|gif)$/i,
                use: [
                    {
                        loader: 'file-loader',
                    },
                ],
            },
            {
                test: /\.less$/i,
                use: [
                    {
                        loader: "style-loader",
                    },
                    {
                        loader: "css-loader",
                    },
                    {
                        loader: "less-loader",
                        options: {
                            lessOptions: {
                                strictMath: true,
                            },
                        },
                    },
                ],
            }         
        ]
    }
};

site.js

// Import JS Dependencies
import 'bootstrap';
import 'jquery';
import 'jquery-validation';

// Import Fonts
import 'font-awesome/css/font-awesome.css';
import '../css/gear-font.css';

// Import CSS Dependencies
import 'bootstrap/dist/css/bootstrap.css';

// Custom Css
import '../css/site.css';
import '../css/main-admin.css';

// Custom Less
import '../less/main.less';

import EventChange from '../js/eventMessage';

console.log('The \'site\' bundle has been loaded!');

eventMessage.js

export function EventChange() {
    console.log("JS Script")
};

Index.cshtml

<div class="card">
     <div class="card-header">
        <h4 class="my-0 fw-normal">@ViewData["Title"]</h4>
    </div>
    <table class="table table-bordered">
        <tr>
            <th scope="col">
                @Html.DisplayName("Sport")
            </th>
            <th scope="col">
                @Html.DisplayName("Last Updated")
            </th>
            <th scope="col">
                @Html.DisplayNameFor(model => model.FirstOrDefault().Enabled)
            </th>
            <th scope="col">
                @Html.DisplayName("Actions")
            </th>
        </tr>
        @foreach (var item in Model) {
            <tr>    
                @Html.HiddenFor(x => item.IdSportType)
                <td>
                    @Html.DisplayFor(x => item.SportType.Name, "Sport")
                </td>
                <td>
                    @{var lastUpdate = item.LastUpdateDate.ToShortDateString();}
                    @Html.DisplayFor(x => lastUpdate, "Last Updated")
                </td>
                <td>
                    @Html.EditorFor(x => item.Enabled, new { @class = "EditCheckbox", onchange = "EventChange()"  })                </td>
                <td>
                    @Html.ActionLink("Edit", "Edit", new { id = item.SportType.IdsportType })
                </td>
            </tr>
        }
    </table>
</div>

CodePudding user response:

In order to access elements, which webpack bundled, you need to add them to the global window variable:

/** ... */
import EventChange from '../js/eventMessage';

window.EventChange = EventChange;
/** ... */

But instead of exposing variables, to the global window variable, you should be better off adding the listener straight in the js file, like this:

/** ... */
import EventChange from '../js/eventMessage';

jQuery('body').on('change', '.EditCheckbox', (event) => {
    EventChange();
});
/** ... */

and remove the onchange attribute from your dom element in your template file.

CodePudding user response:

I got it to work. First I had to make changes to my eventMessage.js file:

import $ from 'jquery';

export function EventChange() {


    console.log("JS Script");
};

$(".EditCheckbox").change(function () {
    console.log("JS Script");
});

I imported my script in my site.js

import '../js/eventMessage.js';

Finally I had to change the checkbox in the HTML:

@Html.EditorFor(x => item.Enabled, new { htmlAttributes = new { @class = "EditCheckbox" } })   
  • Related