[英]jQuery and $ not defined in ASP.NET Core project using webpack
我正在开发一个 ASP.NET 核心项目,最近关闭了 npm 包的默认引导程序和 jQuery 库,以便能够主题引导程序。 但是,我注意到 jQuery 似乎没有正确加载,或者根本没有加载; 像$ is not defined
和jQuery is not defined
这样的错误。
我尝试修复将 webpack 从 v4 更新到 v5,并在条目上使用dependOn,但这也没有解决问题。 我觉得这里应该归咎于加载顺序,但我尝试过的一切都没有奏效。 查看捆绑文件时,总是最后加载 jQuery。
webpack.config.js:
const path = require('path');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const {CleanWebpackPlugin} = require('clean-webpack-plugin');
const bundleFileName = 'bundle';
const dirName = 'wwwroot/dist';
module.exports = (env, argv) => {
return {
mode: argv.mode === "production" ? "production" : "development",
entry: ['./node_modules/jquery/dist/jquery.js', './node_modules/bootstrap/dist/js/bootstrap.bundle.js', './wwwroot/js/site.js', './wwwroot/scss/site.scss', './node_modules/jquery-validation/dist/jquery.validate.js', './node_modules/jquery-validation-unobtrusive/dist/jquery.validate.unobtrusive.js'],
output: {
filename: bundleFileName + '.js',
path: path.resolve(__dirname, dirName)
},
module: {
rules: [
{
parser: {
amd: false,
},
test: /\.s[c|a]ss$/,
use:
[
'style-loader',
MiniCssExtractPlugin.loader,
'css-loader',
{
loader: 'postcss-loader', // Run postcss actions
options: {
postcssOptions: {
plugins: function () { // postcss plugins, can be exported to postcss.config.js
let plugins = [require('autoprefixer')];
if(argv.mode === "production") {
plugins.push(require('cssnano'));
}
return plugins;
}
}
}
},
'sass-loader'
]
}
]
},
plugins: [
new CleanWebpackPlugin(),
new MiniCssExtractPlugin({
filename: bundleFileName + '.css'
})
]
};
};
package.json:
{
"name": "proj2aalst-g3",
"version": "1.0.0",
"scripts": {
"build": "webpack --progress --profile",
"production": "webpack --progress --profile --mode production"
},
"author": "",
"license": "ISC",
"devDependencies": {
"autoprefixer": "^10.0.1",
"clean-webpack-plugin": "^3.0.0",
"css-loader": "^4.3.0",
"cssnano": "^4.1.10",
"file-loader": "^6.1.0",
"mini-css-extract-plugin": "^0.11.2",
"node-sass": "^4.14.1",
"postcss-loader": "^4.0.2",
"sass-loader": "^10.0.2",
"style-loader": "^1.2.1",
"webpack": "^4.44.2",
"webpack-cli": "^3.3.12"
},
"dependencies": {
"@popperjs/core": "^2.9.1",
"bootstrap": "5.0.0-beta2",
"jquery": "3.6.0",
"jquery-validation": "^1.19.3",
"jquery-validation-unobtrusive": "^3.2.12",
"postcss": "^8.2.9"
}
}
您必须将 jQuery 添加到插件中,如下所示:
plugins: [
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery"
})
]
这意味着,如果 webpack 遇到 $ 或 jQuery 它将注入插件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.