能否用Webpack在无后端环境下实现多页面应用及双应用同域分路径部署?
可以用Webpack实现该需求,以下是具体方案
项目结构建议
先整理清晰的目录结构,方便分别维护两个应用:
your-project/ ├── simple-app/ # 纯JS简易应用 │ ├── src/ │ │ ├── index.js │ │ └── index.html │ └── webpack.config.js ├── main-app/ # React主应用 │ ├── src/ │ │ ├── index.jsx │ │ ├── App.jsx │ │ └── index.html │ └── webpack.config.js └── package.json
1. 配置简易应用(simple-app)的Webpack
因为是无依赖纯JS项目,配置极简,核心是指定publicPath匹配部署路径:
// simple-app/webpack.config.js const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: './src/index.js', output: { filename: 'bundle.js', path: path.resolve(__dirname, 'dist'), publicPath: '/simple/' // 必须与部署路径一致 }, mode: 'production', plugins: [ new HtmlWebpackPlugin({ template: './src/index.html', filename: 'index.html' }) ] };
- 安装依赖:
npm install webpack webpack-cli html-webpack-plugin --save-dev - 构建命令:
npx webpack,产物会输出到simple-app/dist
2. 配置主应用(main-app)的Webpack
React应用需要处理JSX和Babel转换,同样要设置对应publicPath:
// main-app/webpack.config.js const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: './src/index.jsx', output: { filename: 'bundle.js', path: path.resolve(__dirname, 'dist'), publicPath: '/main/' // 匹配部署路径 }, mode: 'production', module: { rules: [ { test: /\.(js|jsx)$/, exclude: /node_modules/, use: 'babel-loader' }, { test: /\.css$/, use: ['style-loader', 'css-loader'] } ] }, resolve: { extensions: ['.js', '.jsx'] }, plugins: [ new HtmlWebpackPlugin({ template: './src/index.html', filename: 'index.html' }) ] };
- 安装依赖:
npm install webpack webpack-cli html-webpack-plugin babel-loader @babel/core @babel/preset-env @babel/preset-react style-loader css-loader --save-dev - 构建命令:
npx webpack,产物输出到main-app/dist
3. 部署配置
构建完成后,将两个应用的dist目录内容分别部署到服务器对应路径:
- 将
simple-app/dist下的所有文件放到服务器根目录的simple文件夹 - 将
main-app/dist下的所有文件放到服务器根目录的main文件夹
以Nginx为例,配置路由映射确保访问正确:
server { listen 80; server_name your-domain.com; # 匹配简易应用路径 location /simple { alias /path/to/server/simple; index index.html; try_files $uri $uri/ /simple/index.html; } # 匹配主应用路径 location /main { alias /path/to/server/main; index index.html; try_files $uri $uri/ /main/index.html; } }
关键注意事项
- publicPath必须准确:两个应用的
output.publicPath必须和部署路径完全一致,否则打包后的资源会出现404 - React路由适配:如果主应用使用React Router,需要给
BrowserRouter添加basename属性:import { BrowserRouter } from 'react-router-dom'; ReactDOM.render( <BrowserRouter basename="/main"> <App /> </BrowserRouter>, document.getElementById('root') ); - 脚本简化:可以在根目录的
package.json中添加构建脚本,方便一键构建:{ "scripts": { "build:simple": "cd simple-app && webpack", "build:main": "cd main-app && webpack", "build:all": "npm run build:simple && npm run build:main" } }
内容的提问来源于stack exchange,提问作者Anoush Hakobyan
相关产品推荐
相关产品推荐

