簡體   English   中英

在使用ES6和Webpack 4時,在需要/導入之后“未定義jQuery”

[英]“jQuery is not defined” after require/import when use ES6 with Webpack 4

我正在使用Webpack 4來構建我的React應用程序。 我的應用程序使用jQuery,我想import jQuery插件,但得到以下錯誤:

Failed to compile.

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

我已經嘗試了這里這里描述的方法,但都沒有幫助我。

// app.js

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

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

// jquery-plugin.js

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

如果我理解這種方法在以前的Webpack版本中正常工作。

如果我將import jQuery from 'jquery'添加到jquery-plugin.js進行測試,它可以正常工作,但我不能這樣做,因為它是第三方插件。

有沒有人有想法如何在Webpack 4中全局可見jQuery?

UPD:

我使用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;
};

你需要讓webpack知道它是全局的:

import { ProvidePlugin } from 'webpack';

然后在配置的plugins條目中:

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

這應該解決jquery-plugin.js的問題,你也不需要在任何地方導入jquery

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM