Source maps for devel and production with nodemon (solution) #10
Description
For anyone who has problems getting source maps to work for devel, here is a solution that I just came up with. I am using Node 5.3.
Install the following packages:
$ npm install --save babel-cli babel-preset-es2015 source-map-support
$ npm install --save-dev nodemon
In this example I am using Heroku for production. The reason I put most of the packages in "dependencies" instead of in "devDependencies" to enable Heroku to transpile the js files when it's deployed (so we don't have to check in any dist files). If you don't use Heroku you can use --save-dev
for all the packages.
In your index file (index.js, app.js worker.js etc), add:
import 'source-map-support/register';
Important If you have previously used babel-register hook (eg require('babel-register')
) make sure to remove it or it will skew the line numbers in stack traces.
package.json - The postinstall script transpiles all js files and put the result in dist/. postinstall will run after any npm install
, which Heroku also run when deploying a new version of your app. The start-web and start-worker scripts are for development use and simply tell nodemon to run postinstall (eg. transpiling) on every reload, the transpiled output is then executed.
{
"scripts": {
"start-web": "nodemon dist/app.js --ignore dist/ --exec 'npm run postinstall && node'",
"start-worker": "nodemon dist/worker.js --ignore dist/ --exec 'npm run postinstall && node'",
"postinstall": "babel *.js -d dist"
}
}
Now you can npm run start-web
locally and it will update as files changes, with the correct line numbers in stack traces:
$ npm run start-web
$ npm run start-worker
$ heroku local # Simulate Heroku env locally (no file watch)
Procfile (Heroku only) - since Heroku automatically run the postinstall npm script at deploy time we can simply use vanilla node to run the transpiled files (eg dist/app.js and dist/worker.js):
web: node --optimize_for_size --max_old_space_size=460 --gc_interval=100 dist/app.js
worker: node --optimize_for_size --max_old_space_size=460 --gc_interval=100 dist/worker.js
.gitignore - make sure to exclude the dist folder before committing and deploying to Heroku:
node_modules
dist
I'm not sure if I am missing something, but this is the only way I could source maps and file watcher to work for production and dev, without using additional tools like gulp or such. Curious to if there is a simpler way (is it possible to use source maps with babel-node for example?).