How to bundle a React app to a subdirectory on a server?

前端 未结 10 2109
名媛妹妹
名媛妹妹 2020-12-04 14:41

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.

My webpack config file looks like this..

相关标签:
10条回答
  • 2020-12-04 15:26

    In my situation, I needed to support a scenario, where there might be 0 to many subfolders with unknown names and production uses only static files.

    In my App.js, I defined this simple function:

    const getBasename = path => path.substr(0, path.lastIndexOf('/'));
    

    Which I use to define the basename:

    <Router basename={getBasename(window.location.pathname)}>
    

    This works with no subfolder as well as many subfolders and it can manage reloads as well.

    0 讨论(0)
  • 2020-12-04 15:26

    if you want to install in a sub-directory then you need to specify the basename here is an example.

      <Router basename="/dashboard/">
    
      <Route path="/login" component={Login} />
    

    0 讨论(0)
  • 2020-12-04 15:34

    I had to do something similar recently in order to get a react app running in a sub directory. Try the below and see how you get on.

    import React from 'react';
    import { Router, Route, IndexRoute, useRouterHistory  } from 'react-router';
    import { createHistory } from 'history';
    import VensaDashboard from './components/VensaDashboard';
    import Inbox from './components/Inbox';
    import Todo from './components/Todo';
    import Home from './components/Home';
    
    // specify basename below if running in a subdirectory or set as "/" if app runs in root
    const appHistory = useRouterHistory(createHistory)({
      basename: "/vensa"
    });
    
    export default (
      <Router history={appHistory} />
        <Route path="/" component={VensaDashboard}>
          <IndexRoute component={Home} />
          <Route path="/message" component={Inbox} />
          <Route path="/todo/:todoPage" component={Todo} />
        </Route>
      </Router>
    );
    

    You may also have to update the path to your bundle.js file in index.html as shown below

    <!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>
    
    0 讨论(0)
  • 2020-12-04 15:34
    var sourcePath = path.resolve(__dirname, 'src', 'index.js');
    var buildPath = path.resolve(__dirname, 'vensa');
    
    module.exports = {
        entry: [sourcePath],
        output: {
            path: buildPath,
            filename: '[name]-[hash].js',
            hash: true
        }
        ...
    
    0 讨论(0)
提交回复
热议问题