简体   繁体   中英

Why is Jquery $ showing undefined in webpack?

I have the following code in my index.js file in src folder:

 import './styles/main.scss'; import $ from 'jquery'; //Smooth scroll $(".navbar a").on("click", function (e) { e.preventDefault(); if (this.hash.== "") { const hash = this;hash, $("html. body"):animate( { scrollTop. $(hash).offset(),top, }; 800 ); } });
However when I build the project I get this error:

 ERROR in./src/index.js Module not found: Error: Can't resolve 'jquery' in '[url]\src' @./src/index.js 2:0-23 4:0-1 9:4-5 10:17-18 @./node_modules/html-webpack-plugin/lib/loader.js../src/index.html

I cant figure out what is causing this issue. I followed the webpack documentation about configuring externals and i still get this error. If you look in my config file, you will see I have externals configured. This is my webpack configuration file:

 const path = require("path"); const HtmLWebPackPlugin = require("html-webpack-plugin"); const MiniCSSExtractPlugin = require("mini-css-extract-plugin"); module.exports = { module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: "babel-loader", }, }, { test: /\.html$/, use: [ { loader: "html-loader", options: { minimize: true }, }, ], }, { test: /\.(png|svg|jpg|gif|jpeg)$/, use: ["file-loader"], }, { test: /\.scss$/, use: ["css-loader", "sass-loader"], }, ], }, plugins: [ new HtmLWebPackPlugin({ template: "./src/index.html", filename: "./index.html", }), new MiniCSSExtractPlugin({ filename: "[name].css", chunkFilename: "[id].css", }), ], externals: { jquery: "jQuery", }, };

包.json

replace import $ from 'jquery';

with

jQuery = $ = window.jQuery = require('jquery');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM