使用React-Router的ReactJS生产构建无法正常工作

时间:2019-09-23 15:55:12

标签: reactjs deployment react-router

我用react-router创建了一个简单的应用,其部分如下所示:

                    <BrowserRouter>
                      <Switch>
                        <Route
                            exact
                            path="/"
                            render={() => <Redirect to="/home" />}
                        />
                        {layoutRoutes.map((prop, key) => {
                          return (
                              <Route
                                  path={prop.path}
                                  component={prop.component}
                                  key={key}
                              />
                          );
                        })}
                      </Switch>
                    </BrowserRouter>

但是在构建应用并将其部署到Web服务器时,该页面呈现为白页,甚至没有重定向到/home组件。

该应用程序本身是通过create-react-app创建的,而package.json如下所示:

{
  "name": "front-end",
  "version": "0.1.0",
  "private": true,
  "homepage": ".",
  "dependencies": {
    "bootstrap": "^4.3.1",
    "formik": "^1.5.8",
    "react": "^16.9.0",
    "react-dom": "^16.9.0",
    "react-redux": "^7.1.1",
    "react-router-dom": "^5.0.1",
    "react-router-redux": "^4.0.8",
    "react-scripts": "3.1.1",
    "redux": "^4.0.4",
    "redux-persist": "^6.0.0",
    "redux-thunk": "^2.3.0",
    "yup": "^0.27.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "json-server": "^0.15.1"
  }
}

有什么线索为什么在开发环境中以npm start的身份工作,而在构建和部署时却没有?

1 个答案:

答案 0 :(得分:1)

我发现这很有帮助:

  

如果您使用的是Apache HTTP Server,则需要创建一个.htaccess   公用文件夹中的文件如下所示:

Options -MultiViews
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.html [QSA,L]
     

当您运行build时,它将被复制到npm run build文件夹中。