我正在使用 Webpack 4 构建我的 React 应用程序。
我的应用程序使用 jQuery,我想导入
jQuery 插件,但出现以下错误:
Failed to compile.
./jquery-plugin.js
Line 3: 'jQuery' is not defined no-undef
我已经尝试了描述的方法 here和 here但都没有帮助我。
//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;
};
最佳答案
你需要让 webpack 知道它是一个全局的:
import { ProvidePlugin } from 'webpack';
然后在配置的 plugins
条目中:
plugins: [ new ProvidePlugin({$: 'jquery', jQuery: 'jquery'}) ],
这应该可以解决 jquery-plugin.js
中的问题,您也不需要在任何地方导入 jquery
关于javascript - "jQuery is not defined"在 Webpack 4 中使用 ES6 时需要/导入后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53906419/