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

Create-react-app: how to define context-path of development server

我正在使用带有 npm start 命令的 Create-react-app 在开发服务器中为我的应用程序提供服务。默认情况下,应用程序是从 https://localhost:3000/. However my application uses cookies which requires specific context path. How do I serve the application from https://localhost:3000/app/ 提供的?

您可以根据此处找到的文档,通过添加以下内容来指定路径:"homepage": "http://mywebsite.com/relativepath" 到您的 package.json 文件:

https://create-react-app.dev/docs/deployment/#building-for-relative-paths

这里有几个选项。

生产模式

设置环境变量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/';

步骤 3

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