【发布时间】: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
// 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