如何将ReactJS应用程序部署到Heroku

时间:2018-09-06 14:08:31

标签: reactjs heroku deployment

我正在尝试将reactJS应用程序部署到heroku。我正在本地计算机上进行开发。我的package.json文件中包含以下内容:

from __future__ import print_function
from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools

# If modifying these scopes, delete the file token.json.
SCOPES = 'https://www.googleapis.com/auth/drive.metadata.readonly'

def main():
    """Shows basic usage of the Drive v3 API.
    Prints the names and ids of the first 10 files the user has access to.
    """
    store = file.Storage('token.json')
    creds = store.get()
    if not creds or creds.invalid:
        flow = client.flow_from_clientsecrets('credentials.json', SCOPES)
        creds = tools.run_flow(flow, store)
    service = build('drive', 'v3', http=creds.authorize(Http()))

    # Call the Drive v3 API
    results = service.files().list(
        pageSize=10, fields="nextPageToken, files(id, name)").execute()
    items = results.get('files', [])

    if not items:
        print('No files found.')
    else:
        print('Files:')
        for item in items:
            print('{0} ({1})'.format(item['name'], item['id']))

if __name__ == '__main__':
    main()

在本地计算机上测试时,我从命令提示符下键入“ npm start”,浏览器打开到localhost:8080,应用程序启动。

将应用程序部署到heroku服务并尝试启动该应用程序时,出现应用程序错误。然后,我查看了日志,看到了:

"name": "sample-app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
  "start": "webpack-dev-server --open"
}

我很确定我需要将“开始”脚本更改为其他内容,但是我不知道需要将其更改为什么。我想。

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

您真的不应该使用dev-server尝试在生产环境中运行您的应用程序。我将推出一个简单的Express服务器,并使用它来部署您的应用程序。您可以很快进行设置:

npm i -s express

然后在应用程序结构的顶层创建您的server.js文件。

将此代码放入server.js文件:

const express = require('express')
const app = express()
const path = require('path')
const port = process.env.PORT || 3001

app.use('/', express.static(path.join(__dirname, 'public')))

app.listen(port, () => console.log("Listening on Port", port)) 

从本质上来说,这只是设置您的服务器,然后向其显示在哪里可以找到要用来加载React应用的index.html页面,以便将其发送到浏览器。如果您的Webpack设置将index.html文件输出到“ public”以外的文件夹,只需将该文件夹的名称放在“ __dirname”之后我放置“ public”的位置即可。

现在,您只需要构建您的应用程序即可。

如果您使用的是webpack,就像在package.json中设置“ build”脚本一样简单:

"build": "webpack -p"

然后确保Heroku知道如何将您的构建与另一个脚本一起使用:

"heroku-postbuild": "npm run build"

最后,设置“启动”脚本以运行服务器(Heroku为此默认使用名称“ start”):

"start": node server.js

因此,您的package.json脚本应如下所示:

"scripts": {
    "dev-server": "webpack-dev-server --open"
    "start": "node server.js",
    "build": "webpack -p",
    "heroku-postbuild": "npm run build"
}

现在,如果您将其推送到Heroku,它将可以正常运行。

答案 1 :(得分:0)

我在您的问题Error: spawn EACCES上进行了搜索,发现其他人在使用Heroku时也报告了类似的情况。

尝试在脚本中添加postinstall,以查看是否有帮助。

"name": "sample-app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
  "start": "webpack-dev-server --open",
  "postinstall": "chmod -R +x node_modules/next/dist/bin/next-* && npm run build",
}

如果这不起作用,您可以查看original thread here,看看是否有其他解决方案适合您。