如何将React应用程序部署到服务器的子目录

如何将React应用程序部署到服务器的子目录
最近一直在写React的应用程序。本地开发的时候一直使用的是根路径访问(http://localhost:3000),但是部署到测试环境的时候,由于使用了子目录(http://192.168.100.36:3000/reactapp),访问的时候就出现了空白页的问题。那么在React中如何实现子目录也能访问呢?

经过搜索和阅读一些文档后,终于找到了解决办法!下面是我的方法,希望对大伙学习React有所帮助。

应用信息

我这里的应用是使用create-react-app创建并且react版本为16.6.1、react-router版本为4.3.1

1.在路由指定子目录路径

<Router/>组件上设置basename属性,告诉React Router将从指定子目录提供应用程序,示例:

<Router basename={'/reactapp'}>
            <Route exact path="/" component={Home}/>
             <Route path="/news" component={News}/>
            <Route path="/about" component={About}/>
            {/* … */}
            <Route component={NoMatch}/>
</Router>

这里的reactapp就是子目录名称。

2.设置应用的homepage属性

package.json中设置homepage属性,指定主页路径,示例:

{
  "name": "my-react-app",
  "version": "0.1.0",
  "homepage": "http://192.168.100.36:3000/reactapp",
  "private": true,
  //...这里省略package.json的其它代码...
}

指定了该属性过后就会在执行npm run build打包时候看到如下提示:

The project was built assuming it is hosted at /reactapp/.
You can control this with the homepage field in your package.json.

这里设置homepage属性的目的就是为了限制访问路径。

3.在路由中指定全路径

在步骤2中设置的homepage值可以通过获取环境变量的方式process.env.PUBLIC_URL取得。我们就可以在 <Route/>中指定全路径了,示例:

<Router basename={'/reactapp'}>
      <Route path={`${process.env.PUBLIC_URL}/`} component={Home} />
      <Route path={`${process.env.PUBLIC_URL}/news`} component={News} />
      <Route path={`${process.env.PUBLIC_URL}/about`} component={About} />
       {/* … */}
      <Route component={NoMatch}/>
</Router>

4.链接修改为全路径方式

整个应用会有很多<Link/>组件,我将这些Link也都改成全路径方式,示例:

<Link to={`${process.env.PUBLIC_URL}/news`}>新闻</Link>
<Link to={`${process.env.PUBLIC_URL}/about`}>关于我们</Link>

通过以上的修改,整个应用就可以部署到你想的任何子目录了。

the end

热门文章