在Google App Engine上部署create-react-app

14

我希望将使用create-react-app创建的应用程序部署到Google App Engine。

我的应用程序在本地上运行良好(包括npm startnpm run build & serve -s build)。 然而,在Google App Engine上部署的应用程序仅显示index.html,并且没有调用我的react代码。

Chrome开发者控制台显示了Uncaught SyntaxError: Unexpected token <

此外,我在console.cloud.google.com上发现,部署的应用程序未包含构建文件夹。这是正确的吗?

有人能解决这个问题吗?

这是我的package.json:

{
  "name": "XXXXX",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "react": "^16.8.2",
    "react-dom": "^16.8.2",
    "react-ga": "^2.5.7",
    "react-router-dom": "^4.3.1",
    "react-scripts": "2.1.5"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
 },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": [
    ">0.2%",
    "not dead",
    "not ie <= 11",
    "not op_mini all"
  ]
}

另外,这是我的app.yaml文件。

runtime: nodejs10

handlers:
- url: /.*
  static_files: build/index.html
  upload: build/index.html
- url: /
  static_dir: build

1
你在部署之前是否执行了 npm run build 命令? - Help
我试过了,但是没有起作用... - Daisuke SHIBATO
2个回答

25
由于多次搜索网络,我发现我的React应用的路由系统是问题的原因。
正如这篇文章所述,我们需要小心撰写app.yaml。如果我们首先编写以下内容,GAE将返回build/index.html的所有查询,包括访问/static/js/static/css
- url: /
  static_files: build/index.html
  upload: build/index.html

create-react-app会为npm run build创建一个构建文件夹和静态子文件夹。因此,我需要像这样更具体地编写我的app.yaml:

handlers:
  - url: /static/js/(.*)
    static_files: build/static/js/\1
    upload: build/static/js/(.*)
  - url: /static/css/(.*)
    static_files: build/static/css/\1
    upload: build/static/css/(.*)
  - url: /static/media/(.*)
    static_files: build/static/media/\1
    upload: build/static/media/(.*)
  - url: /(.*\.(json|ico))$
    static_files: build/\1
    upload: build/.*\.(json|ico)$
  - url: /
    static_files: build/index.html
    upload: build/index.html
  - url: /.*
    static_files: build/index.html
    upload: build/index.html

1
请编辑答案并放置完整的app.yaml文件。您在runtime中放置了什么? - fsbflavio

7

1
@Daisuke SHIBATO - 添加了 .yaml 文件和参考链接以使事情更清晰。 - Harsh Makadia
嗨Harsh,感谢您的评论。我发现这个问题的原因是我在GAE上路由React应用程序。 - Daisuke SHIBATO
很高兴您的问题得到了解决。如果此答案对您有帮助,请接受它,以便其他遇到类似问题的人也可以从中受益。 - Harsh Makadia
尝试上传所有的node_modules吗? - Oliver Dixon
不,它不应该。 - Harsh Makadia

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