Jquery $为什么在webpack中显示未定义?

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

我在src文件夹中的index.js文件中具有以下代码:

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
      );
    }
  });
  
但是,当我构建项目时,出现此错误:

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

我不知道是什么原因导致了这个问题。我遵循有关配置外部组件的webpack文档,但仍然收到此错误。如果查看我的配置文件,将会看到我已配置了外部设备。这是我的webpack配置文件:

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",
  },
};

Package.json

javascript jquery webpack webpack-dev-server
1个回答
0
投票

替换import $ from 'jquery';

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

© www.soinside.com 2019 - 2024. All rights reserved.