我已经创建了一个示例项目repo https://github.com/nikhilgoswami/webpack-5-react-with-jquery-plugin.git
我得到错误jQuery是没有定义时,导入插件flexslider
我尝试了expose-loader和provider -plugin,但是没有用
将以下配置添加到你的webpack.config.js文件中,以确保jQuery可以被全局访问并被你的应用程序使用:
const webpack = require('webpack');
module.exports = {
// ...
plugins: [
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery',
}),
],
// ...
};
在React组件中,导入jQuery和Flexslider:
import $ from 'jquery';
import 'flexslider';
class MyComponentClass extends React.Component {
componentDidMount() {
// Initialize Flexslider
$(this.slider).flexslider();
}
render() {
return (
<div ref={(slider) => { this.slider = slider; }}>
// Slides go here
</div>
);
}
}
export default MyComponentClass;
确保在服务器上渲染React组件时包含Flexslider所需的CSS和JavaScript文件:
import MyComponent from './MyComponentClass';
import fs from 'fs';
import path from 'path';
// Read the Flexslider's JavaScript and CSS files.
const flexsliderCss = fs.readFileSync(path.resolve(__dirname,
const flexsliderJs = fs.readFileSync(path.resolve(__dirname,
'../node_modules/flexslider/jquery.flexslider.js'), 'utf8');
// Render the React component and include the CSS and JavaScript files for
Flexslider
const html = ReactDOMServer.renderToString(
<MyComponent />,
);
const finalHtml = `
<!DOCTYPE html>
<html>
<head>
<title>My Application</title>
<style>${flexsliderCss}</style>
</head>
<body>
<div id="app">${html}</div>
<script src="/bundle.js"></script>
<script>${flexsliderJs}</script>
</body>
</html>
`;
res.send(finalHtml);
首先你可以使用下面的命令安装插件
npm install jquery flexslider --save
然后创建新文件jquery-global.js在SRC文件夹中,并在下面放置代码
import $ from 'jquery';
window.jQuery = $;
window.$ = $;
需要Webpack配置文件Webpack .config.js添加以下代码并根据需要进行配置
const webpack = require('webpack');
const path = require('path');
module.exports = {
plugins: [
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
}),
],
};
在server.js中添加以下代码文件
import jquery from 'jquery';
global.$ = global.jQuery = jquery;
这是你更新的代码,你可以试试这个
import React, { Component } from 'react';
import $ from 'jquery';
import 'flexslider';
class FlexSlider extends Component {
componentDidMount() {
$(this.slider).flexslider({
animation: "slide",
slideshowSpeed: 3000,
controlNav: false,
directionNav: true,
prevText: "",
nextText: ""
});
}
render() {
return (
<div className="flexslider" ref={slider => (this.slider = slider)}>
<ul className="slides">
<li><img src="http://example.com/slide1.jpg" alt="Slide 1" /></li>
<li><img src="http://example.com/slide2.jpg" alt="Slide 2" /></li>
<li><img src="http://example.com/slide3.jpg" alt="Slide 3" /></li>
</ul>
</div>
);
}
}
export default FlexSlider;
我希望它应该是工作