如何在 Webpack 中设置 jQuery 并在 .cshtml 文件中使用?

问题描述 投票:0回答:1

我正在致力于在 ASP.NET Core MVC 应用程序中设置 webpack。将 jQuery 安装为依赖项后,我在尝试使用 jQuery 的任何地方都会收到错误:

未捕获的引用错误:$未定义

当我查看

site.entry.js
时,我可以看到 jQuery 已包含在捆绑包中。我将脚本标记设置为指向该文件,并且还捆绑了 Bootstrap,并且工作正常。

脚本标签位于

_Layout.cshtml
内部:

<head>
    <script src="/dist/site.entry.js" defer></script>
</head>

在我的

site.js
中,我添加了以下导入:

// JS Dependencies: Popper, Bootstrap & JQuery
import '@popperjs/core';
import 'bootstrap';
import 'jquery';
// Using the next two lines is like including partial view _ValidationScriptsPartial.cshtml
import 'jquery-validation';
import 'jquery-validation-unobtrusive';

// CSS Dependencies: Bootstrap & Bootstrap icons
import 'bootstrap-icons/font/bootstrap-icons.css';
import 'bootstrap/dist/css/bootstrap.css';

这是

package.json
:

{
  "name": "TestProject",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@popperjs/core": "^2.11.8",
    "bootstrap": "^5.3.3",
    "bootstrap-icons": "^1.11.3",
    "jquery": "^3.7.1",
    "jquery-validation": "^1.21.0",
    "jquery-validation-unobtrusive": "^4.0.0"
  },
  "devDependencies": {
    "css-loader": "^7.1.2",
    "eslint": "^9.5.0",
    "expose-loader": "^5.0.0",
    "mini-css-extract-plugin": "^2.9.1",
    "style-loader": "^4.0.0",
    "url-loader": "^4.1.1",
    "webpack": "^5.93.0",
    "webpack-cli": "^5.1.4"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack"
  }
}

这就是

webpack.config.js

const path = require('path');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const webpack = require('webpack');

module.exports = {
    entry: {
        site: './wwwroot/js/site.js'
    },
    output: {
        filename: '[name].entry.js',
        path: path.resolve(__dirname, 'wwwroot', 'dist'),
        clean: true
    },
    devtool: 'source-map',
    mode: 'development',
    plugins: [
        new MiniCssExtractPlugin(),   
        new webpack.ProvidePlugin({
            $: 'jquery',
            jQuery: 'jquery'
      })],
    module: {
        rules: [
            {
                test: /\.css$/i,
                use: [MiniCssExtractPlugin.loader, 'css-loader']
            },
            {
                test: /\.(png|svg|jpg|jpeg|gif|webp)$/i,
                type: 'asset/resource',
                generator: {
                    // keep original filenames and copy images to dist/images/
                    filename: 'images/[name][ext]'
                }
            },
            {
                test: /\.(eot|woff(2)?|ttf|otf)$/i,
                type: 'asset/resource',
                generator: {
                // keep original filenames and copy fonts to dist/fonts/
                filename: 'fonts/[name][ext]'
                }
            },
            {
                // Exposes jQuery for use outside Webpack build
                test: require.resolve('jquery'),
                loader: "expose-loader", options: { exposes: ["$", "jQuery"], }
              }
        ]
    }
};

我正在尝试在我的其他一些视图中使用 jQuery。例如,我有一个

Profile.cshtml
,它在文件底部有一个脚本标记。

// html code is above the script tag
<script type="text/javascript">
    const accountDetailsModal = document.getElementById("editAccountModal");
    const selectedState = "@Model.AccountProfile.State";
    accountDetailsModal.addEventListener("show.bs.modal", event => {
        let stateField = document.getElementById("State");
        stateField.value = selectedState;
    });


    $("#editAccountModal").on("submit", "#form-accountprofileedit", function (e) {
        e.preventDefault();
        var form = $(this);
        $.ajax({
            url: form.attr("action"),
            method: form.attr("method"),
            data: form.serialize(),
            success: function (partialResult) {
                $("#formContent").html(partialResult);
            }
        });
    });
</script>

我不确定我做错了什么或者我可能会错过什么。

jquery asp.net-core webpack asp.net-core-mvc
1个回答
0
投票

删除

defer
可以解决问题。

<head>
    <script src="/dist/site.entry.js" ></script>
</head>
© www.soinside.com 2019 - 2024. All rights reserved.