在 WebPack 中添加自定义 Js 并通过 MVC HTML helper 使用它

Adding custom Js in WebPack and using it via MVC HTML helper

我是 WebPack 新手:我有一个使用 DotNet Core 的 MVC 5 项目。我的前端全部是 HTML 和 bootstrap 的 Razor,css。我设置了 webpackconfig.js 和 site.js。所有这些都适用于 NPM 包。当我尝试添加我们自己的 CDN 或本地 JS 文件时,我无法访问我创建的函数。我发布了 webpackconfig.js、site.js、我的 custom.js 和 html.

我正在尝试向我的 EditFor 添加一个 onchange。我没有收到任何错误。我只是不确定我应该如何调用该 JS 函数。

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>

为了访问 webpack 捆绑的元素,您需要将它们添加到全局 window 变量中:

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

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

但是,与其将变量暴露给全局 window 变量,不如直接在 js 文件中添加监听器,如下所示:

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

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

并从模板文件中的 dom 元素中删除 onchange 属性。

我让它工作了。首先,我必须更改我的 eventMessage.js 文件:

import $ from 'jquery';

export function EventChange() {


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

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

我在 site.js

中导入了我的脚本
import '../js/eventMessage.js';

最后我不得不更改 HTML 中的复选框:

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