【问题标题】:"jQuery is not defined" after require/import when use ES6 with Webpack 4将 ES6 与 Webpack 4 一起使用时,在 require/import 之后“未定义 jQuery”
【发布时间】:2019-05-23 04:52:25
【问题描述】:

我正在使用 Webpack 4 来构建我的 React 应用程序。 我的应用程序使用 jQuery,我想 import jQuery 插件但得到以下错误:

Failed to compile.

./jquery-plugin.js
  Line 3:  'jQuery' is not defined  no-undef

我尝试了herehere 描述的方法,但都没有帮助我。

// app.js

import $ from 'jquery';
// import './jquery-plugin.js';
window.$ = window.jQuery = $;

require('./jquery-plugin.js');

// jquery-plugin.js

(function($) {
  // Plugin code
})(jQuery);

如果我理解 this approach 在以前的 Webpack 版本中可以正常工作。

如果我将 import jQuery from 'jquery' 添加到 jquery-plugin.js 进行测试,它可以正常工作,但我不能这样做,因为它是第 3 方插件。

有没有人知道如何让 jQuery 在 Webpack 4 中全局可见?

更新:

我使用 react-app-rewired 覆盖 Webpack 配置。这是我的配置:

// config-overrides.js

const webpack = require('webpack');

module.exports = function override(config, env) {
  //do stuff with the webpack config...

  config.module.rules.push({
    // Exposes jQuery for use outside Webpack build
    test: require.resolve('jquery'),
    use: [{
      loader: 'expose-loader',
      options: 'jQuery'
    },{
      loader: 'expose-loader',
      options: '$'
    }]
  });

  config.plugins.push(
    new webpack.ProvidePlugin({
    //provide jquery in all the ways 3rd party plugins might look for it (note that window.$/window.jQuery will not actually set it on the window, which is cool)
    '$': 'jquery',
    'jQuery': 'jquery',
    'window.jQuery': 'jquery',
    'window.$': 'jquery'
  }));

  config.resolve = {
    alias: {
      'jquery-ui': 'jquery-ui-dist/jquery-ui.js'
    },
  };

  return config;
};

【问题讨论】:

    标签: javascript jquery reactjs webpack-4


    【解决方案1】:

    你需要让 webpack 知道它是一个全局的:

    import { ProvidePlugin } from 'webpack';
    

    然后在您的配置的plugins 条目中:

    plugins: [ new ProvidePlugin({$: 'jquery', jQuery: 'jquery'}) ],
    

    这应该可以解决jquery-plugin.js 中的问题,并且您也不需要在任何地方导入jquery

    【讨论】:

    • 更新了我的问题。
    • ProvidePlugin 配置中的 window.jQuerywindow.$ 是多余的。您收到的错误消息看起来像是 eslint 问题 - 确保 $jQuery 在您的 eslint 配置的 globals 部分中
    • 我在项目根目录中创建了.eslintrc,添加了{ "env": { "jquery": true }, "globals": { "jQuery": true, "$": true } },重新运行npm start,但没有任何改变。也许,你在 确保 $ 和 jQuery 在你的 eslint 配置的 globals 部分中是不是还有别的意思
    • 不,我就是这个意思。 jquery 在你的 package.json 中吗?
    • 是的,我有"jquery": "^3.3.1",
    猜你喜欢
    • 2019-09-27
    • 1970-01-01
    • 1970-01-01
    • 2018-10-02
    • 2017-03-10
    • 2017-09-25
    • 2019-12-14
    • 2014-10-23
    • 1970-01-01
    相关资源
    最近更新 更多