1

I successfully deployed my Django project to Heroku. But I want to be able to automatically build React before deploying.

The React app is served through Django, so I have the bundled files of React in my templates and static folders of the Django app.

The project structure looks something like this:

react/
  build/
  components/
  App.js
  package.json
  ...
django/
  templates/
  static/
  ...
Procfile
requirements.txt
Pipfile

I have both the React and Django projects in the same repository and I want to run npm run build automatically before Django is deployed.

I set up the build script to move the bundled files from React to Django.

From what I've read, I need to add the NodeJS buildpack, but I don't know how to set it up to run before the Python buildpack.

Basically, the NodeJS process should just build my React app and then terminate. After that, the Python process should start up and deploy the Django project.

One solution to do this would be to use Docker and deploy that image to Heroku.
But, is there an easier way?

2 Answers 2

2

You can add indexed buildpacks in heroku. Take a look here for adding multiple buildpacks to your project.

I wrote a simple tutorial on how one can deploy a React + Django app to Heroku. You can take a look if you're interested. In your case, you only need the instructions for adding the buildpacks.

$ heroku buildpacks:add --index 1 heroku/nodejs
$ heroku buildpacks:add --index 2 heroku/python

You don't need to setup any extra commands to build the React app. Heroku automatically installs and runs the build script from your package.json file(If it's in the project root).

Sign up to request clarification or add additional context in comments.

2 Comments

I have the package.json in the react/ folder so it's not in the project root. Can I tell Heroku the working directory for the nodejs buildpack? If not, I might try to change the structure so that package.json is in the root directory
You might be able to achieve that by modifying the Procfile. This might help you.
0

I found a way to do this.
I added the nodejs buildpack as the first one and then I created a package.json file in the root directory:

{
  "name": "myapp",
  "version": "1.0.0",
  "scripts": {
    "build": "cd react && npm install && npm run build"
  },
  "dependencies": {},
  "devDependencies": {},
  "cacheDirectories": [
    "node_modules",
    "react/node_modules"
  ]
}

Heroku is looking for a package.json in the root directory and automatically runs the build command.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.