react实现多页面
React 实现多页面应用
React 通常用于构建单页面应用(SPA),但通过配置可以实现多页面应用(MPA)。以下是几种常见方法:
使用 Webpack 多入口配置
在 Webpack 配置中设置多个入口文件,每个入口对应一个页面:
// webpack.config.js
module.exports = {
entry: {
page1: './src/page1.js',
page2: './src/page2.js'
},
output: {
filename: '[name].bundle.js',
path: __dirname + '/dist'
}
};
为每个页面创建对应的 HTML 模板,使用 html-webpack-plugin 生成多个 HTML 文件:
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
plugins: [
new HtmlWebpackPlugin({
template: './src/page1.html',
filename: 'page1.html',
chunks: ['page1']
}),
new HtmlWebpackPlugin({
template: './src/page2.html',
filename: 'page2.html',
chunks: ['page2']
})
]
};
使用 Create React App (CRA) 自定义配置
通过 react-app-rewired 覆盖 CRA 的默认配置:
// config-overrides.js
const { override } = require('customize-cra');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = override(
(config) => {
config.entry = {
main: './src/index.js',
about: './src/about.js'
};
config.plugins.push(
new HtmlWebpackPlugin({
template: './public/index.html',
filename: 'about.html',
chunks: ['about']
})
);
return config;
}
);
使用路由实现伪多页面
虽然仍是 SPA,但可以通过路由模拟多页面体验:
// App.js
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
function App() {
return (
<Router>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
</Switch>
</Router>
);
}
静态站点生成方案
使用 Gatsby 或 Next.js 等框架生成静态页面:
// Next.js 页面路由
/pages/index.js → /
/pages/about.js → /about
/pages/contact.js → /contact
部署多页面应用
确保服务器配置正确处理多个 HTML 文件:
# Nginx 配置示例
server {
location / {
try_files $uri /index.html;
}
location /about {
try_files $uri /about.html;
}
}
以上方法可根据项目需求选择,Webpack 多入口适合传统 MPA,路由方案适合内容相关的多视图应用,静态生成适合内容型网站。







