如何将 React 应用程序捆绑到服务器上的子目录? [英] How to bundle a React app to a subdirectory on a server?
问题描述
我在本地主机上开发了一个 React 应用程序.我想将它复制到服务器上的一个名为 vensa 的子目录中.
I have a React app I've been developing on my localhost. I want to copy it to a server into a subdirectory called vensa.
我的 webpack 配置文件看起来像这样..
My webpack config file looks like this..
const ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
entry: [
'./src/index.js'
],
output: {
path: 'build',
filename: 'bundle.js'
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel'
},
{
test: /\.scss$/,
loader: ExtractTextPlugin.extract('style', 'css!sass')
},
{
test: /\.css$/,
loader: ExtractTextPlugin.extract('style', 'css')
},
{
test: /\.(png|eot|svg|ttf|woff(2)?)(\?v=\d+\.\d+\.\d+)?/,
loader: 'url'
}
]
},
plugins: [
new ExtractTextPlugin('vensa-dashboard.css')
],
devServer: {
historyApiFallback: true,
contentBase: './build'
}
};
index.html 文件看起来像这样...
The index.html file looks like this...
<!DOCTYPE html>
<html>
<head>
<title>Vensa Development Test</title>
<link rel="stylesheet" href="/vensa-dashboard.css">
</head>
<body>
<div class="container"></div>
<script src="/bundle.js"></script>
</body>
</html>
我的 routes.js 文件是...
and my routes.js file is...
import React from 'react';
import { Route, IndexRoute } from 'react-router';
import VensaDashboard from './components/VensaDashboard';
import Inbox from './components/Inbox';
import Todo from './components/Todo';
import Home from './components/Home';
export default (
<Route path="/" component={VensaDashboard}>
<IndexRoute component={Home} />
<Route path="/message" component={Inbox} />
<Route path="/todo/:todoPage" component={Todo} />
</Route>
);
但是,如果我只运行 webpack -p
并将 3 个文件复制到该子目录,则它不起作用,因为根路径是 /
并且它找不到js和css文件.我不确定更改(可能是这 3 个文件中的一个或所有文件)以使其在子目录中工作的(最佳方法)是什么?
However, if I do just run webpack -p
and copy the 3 files over to that subdirectory, it doesn't work as the root path is /
and it can't find the js and css files. I'm not sure what (the best way) to change in (probably one or all of these 3 files) to get it to work in a subdirectory?
应用的完整源代码在这里,以防万一.
The full source code of the app is here in case that helps.
谢谢!
推荐答案
如果您使用的是 React Router v4,您应该能够使用 basename={foobar
} 进行设置.
If you are using React Router v4 you should be able to set it using basename={foobar
}.
<Router history={browserHistory} basename={'foobar'}>
<Route path="/" component={App} />
</Router>
文档链接:https://reacttraining.com/react-router/web/api/BrowserRouter
注意:如果在子目录中使用 create-react-app,您还将想要在 package.json 文件中设置 "homepage": "/foobar/",
.因此,生产构建指向正确的路径.
Note: if using create-react-app in a sub directory you will also want to set "homepage": "/foobar/",
in your package.json file. So the production build points at the right path.
这篇关于如何将 React 应用程序捆绑到服务器上的子目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!