【问题标题】:ReactJS production build with react-router not working使用 react-router 的 ReactJS 生产构建不起作用
【发布时间】:2019-09-23 15:55:12
【问题描述】:

我用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-apppackage.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 的开发环境中工作,但在构建和部署时却没有?

【问题讨论】:

  • 尝试删除“主页”:“。”来自packages.json
  • @Satif 我已经这样做了,而且更糟糕的是 - 没有加载任何静态 CSS 或 JS

标签: reactjs deployment react-router


【解决方案1】:

我发现这很有帮助:

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

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

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

【讨论】:

    猜你喜欢
    • 2021-12-18
    • 2017-09-03
    • 2021-07-20
    • 2019-07-02
    • 1970-01-01
    • 2018-02-07
    • 2017-11-13
    • 2017-05-05
    • 2018-01-18
    相关资源
    最近更新 更多