[英]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.