如何将 React 应用程序捆绑到服务器上的子目录?

新手上路,请多包涵

我有一个我一直在本地主机上开发的 React 应用程序。我想将它复制到服务器的一个名为 vensa 的子目录中。

我的 webpack 配置文件看起来像这样..

 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 文件如下所示…

 <!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 文件是…

 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 文件。我不确定要更改什么(最好的方法)(可能是这三个文件中的一个或全部)以使其在子目录中工作?

该应用程序的完整源代码在 这里,以防万一。

谢谢!

原文由 magician11 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 288
1 个回答

如果您使用的是 React Router v4,您应该能够使用 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/", 。所以生产构建指向正确的路径。

原文由 trenthogan 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题