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