React-Redux导入类失败:适配Egghead Redux入门教程到Express服务器
解决React-Redux导入问题并部署到Express服务器
我明白你想把Egghead的Redux入门代码从JSBin迁移到自己的Express服务器的需求——毕竟能落地的学习才更有价值!你遇到的React-Redux无法导入类的问题,根源在于JSBin用的是全局变量引入方式(直接从window.ReactRedux解构),而本地Express项目通常采用模块化的导入系统(ES6 import 或 CommonJS require),下面是一步步的解决方案:
1. 初始化项目并安装依赖
首先创建项目文件夹,初始化npm并安装所需依赖:
mkdir redux-express-demo cd redux-express-demo npm init -y npm install express react react-dom redux react-redux # 安装开发依赖(用于转译React和打包) npm install --save-dev webpack webpack-cli babel-loader @babel/core @babel/preset-env @babel/preset-react html-webpack-plugin
2. 调整导入方式(替换全局变量写法)
JSBin里的代码依赖全局挂载的ReactRedux和Redux对象,在本地项目中需要改成模块化导入:
如果你用ES6模块(推荐)
在你的React组件文件(比如src/App.js)顶部添加:
import React from 'react'; import { connect, Provider } from 'react-redux'; import { combineReducers, createStore } from 'redux';
如果你用CommonJS(Node.js默认)
如果项目未配置ES6模块支持,改用require:
const React = require('react'); const { connect, Provider } = require('react-redux'); const { combineReducers, createStore } = require('redux');
3. 搭建Express服务器
创建server.js文件,配置Express提供静态资源并启动服务:
const express = require('express'); const path = require('path'); const app = express(); const PORT = 3000; // 托管打包后的静态文件 app.use(express.static(path.join(__dirname, 'dist'))); // 根路由返回HTML页面 app.get('/', (req, res) => { res.sendFile(path.join(__dirname, 'dist', 'index.html')); }); app.listen(PORT, () => { console.log(`Server running on http://localhost:${PORT}`); });
4. 配置Webpack打包(处理React代码)
创建webpack.config.js,用于转译JSX并打包前端代码:
const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: './src/index.js', output: { path: path.resolve(__dirname, 'dist'), filename: 'bundle.js', }, module: { rules: [ { test: /\.(js|jsx)$/, exclude: /node_modules/, use: { loader: 'babel-loader', options: { presets: ['@babel/preset-env', '@babel/preset-react'], }, }, }, ], }, plugins: [ new HtmlWebpackPlugin({ template: './public/index.html', }), ], resolve: { extensions: ['.js', '.jsx'], }, };
5. 编写前端核心代码(对应JSBin示例)
- 创建
public/index.html作为模板:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Redux Express Demo</title> </head> <body> <div id="root"></div> </body> </html>
- 创建
src/index.js挂载React组件:
import React from 'react'; import ReactDOM from 'react-dom/client'; import { Provider } from 'react-redux'; import { combineReducers, createStore } from 'redux'; import App from './App'; // 复制JSBin中的reducer代码 const counterReducer = (state = 0, action) => { switch (action.type) { case 'INCREMENT': return state + 1; case 'DECREMENT': return state - 1; default: return state; } }; const rootReducer = combineReducers({ counter: counterReducer, }); const store = createStore(rootReducer); const root = ReactDOM.createRoot(document.getElementById('root')); root.render( <Provider store={store}> <App /> </Provider> );
- 创建
src/App.js编写组件(对应JSBin中的UI部分):
import React from 'react'; import { connect } from 'react-redux'; const App = ({ count, increment, decrement }) => ( <div> <h1>Count: {count}</h1> <button onClick={increment}>+</button> <button onClick={decrement}>-</button> </div> ); const mapStateToProps = (state) => ({ count: state.counter, }); const mapDispatchToProps = (dispatch) => ({ increment: () => dispatch({ type: 'INCREMENT' }), decrement: () => dispatch({ type: 'DECREMENT' }), }); export default connect(mapStateToProps, mapDispatchToProps)(App);
6. 启动项目
在package.json中添加脚本:
"scripts": { "build": "webpack --mode production", "start": "node server.js", "dev": "webpack --mode development && node server.js" }
然后运行:
npm run dev
访问http://localhost:3000就能看到和JSBin一样的效果了!
常见问题排查
- 如果还是出现导入错误,检查是否安装了所有依赖,或者babel配置是否正确。
- 若使用ES6模块,确保
package.json中添加了"type": "module"(但注意Express的server.js也要改成ES6导入)。
内容的提问来源于stack exchange,提问作者trogne
相关产品推荐
相关产品推荐

