37

I'm using webpack.

Also I don't commit npm_modules folder and public folder, where all generated files are. And I can't figure out how to build my app (I have webpack build command) after deploy and setup my server (it's already looking for public folder).

It seems me a bad idea to commit before upload. Maybe there are some gentle decisions... Any thoughts?

Forked from: How to deploy node that uses Gulp to heroku

Community
  • 1
  • 1
Inanc Gumus
  • 25,195
  • 9
  • 85
  • 101

3 Answers3

66
"heroku-postbuild": "webpack -p --config ./webpack.prod.config.js --progress"

this is better because if you use postinstall, everytime you do npm i the build script get fired

Gaurav Mukherjee
  • 6,205
  • 2
  • 23
  • 33
  • 4
    I was looking for a way to avoid building the app with webpack every time I was installing the dependencies, this is the right way to do it as per the Heroku doc (https://devcenter.heroku.com/articles/nodejs-support#heroku-specific-build-steps). – Jean-Christophe Oct 17 '16 at 09:08
  • All the other answers on StackOverflow use `postinstall`. This is the best answer for all of them. – Kevin Ghadyani Oct 30 '18 at 04:57
14

Do it in a postinstall script as suggested by @orlando:

"postinstall": "webpack -p --config ./webpack.prod.config.js --progress"

In this approach make sure to heroku config:set NODE_ENV=production heroku config:set NPM_CONFIG_PRODUCTION=true

OR

You can find this custom buildpack heroku-buildpack-webpack usable.

These links might help you build understanding:

Zeeshan Hassan Memon
  • 8,105
  • 4
  • 43
  • 57
4

In 2019, the simplest way to do this is to use the heroku/nodejs buildpack (automatically selected if you have a package.json at the root of the repository) and add a build script to package json:

"build": "webpack --mode production --config ./webpack.prod.config.js"

Heroku will automatically run this script on deploy. Bonus points because this is the intuitive script to run to test the build locally or in CI.

This is described in Heroku's Best Practices for Node.js Development document:

npm’s lifecycle scripts make great hooks for automation. Heroku provides custom hooks that allow you to run custom commands before or after we install your dependencies. If you need to run something before building your app, you can use the heroku-prebuild script. Need to build assets with grunt, gulp, browserify, or webpack? Do it in a build script.

ford
  • 10,687
  • 3
  • 47
  • 54