Create-react-app:如何定义开发服务器的上下文路径

6

我正在使用Create-react-app,通过npm start命令在开发服务器中提供我的应用程序。默认情况下,应用程序从https://localhost:3000/提供。但是,我的应用程序使用需要特定上下文路径的Cookie。我怎样才能将应用程序从https://localhost:3000/app/提供出来呢?

3个回答

3

3

在这里您有几个选项。

生产模式

将环境变量PUBLIC_PATH设置为/app/

或者

如其他答案中所述,在package.json中使用homepage字段

开发模式

配置被硬编码到应用程序中。您需要先运行eject以进行任何编辑。

步骤1

npm run eject

步骤2

config/webpack.config.js中,找到下面的部分(大约在第67-68行附近)

const publicPath = isEnvProduction
    ? paths.servedPath
    : isEnvDevelopment && '/';

改为

 const publicPath = isEnvProduction
        ? paths.servedPath
        : isEnvDevelopment && '/app/';
步骤三

config/webpackDevServer.config.js文件中,找到以下部分(大约在60-65行附近):

 // It is important to tell WebpackDevServer to use the same "root" path
 // as we specified in the config. In development, we always serve from /.
 publicPath: '/',

并更改为

publicPath: '/app',

步骤 4

npm start

1
答案中指向的环境变量无效。我在工具文档中找到了PUBLIC_URL,它似乎可以胜任这项工作。 - Miroslav Nedyalkov

0

我已经用以下方法解决了这个问题:

<BrowserRouter basename="/app" />
<Link to="/test" />

使用此解决方案,该 Link 路径为 /app/test

另一个例子:

<BrowserRouter basename="/app">
    <Routes>
        <Route element={<Home />} path="/" exact />
        <Route element={<Test />} path="/test" />
    </Routes>
</BrowserRouter>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接