Overview
I started working in node.js few months back and not surprisingly needed a way to include config transformations in my node.js application. Here's a quick way to get this to work if you're struggling.
Solution
- Create a config folder at the root of your application directory folder. This folder will be used to store all config transforms for various environments (e.g. local, dev, stage, prod). You can organize and name them as you wish but here's what I have done.
-
The index.js is going to be the entry point. This file will look at the current node environment and use an appropriate transform file when your node.js application runs. I'd highly recommend using cross-env package as it will make it much easier to set NDOE_ENV variable.
Here's my index.js file:
// determine the node process environment (default to local if it isn't set) const env = process.env.NODE_ENV || 'local'; const cfg = require(`./config.${env}`); module.exports = cfg;
config.global.js file:
const config = (module.exports = {}); config.env = 'local'; config.port = 3000;
And here's one of the environment specific file:
const config = require('./config.global'); config.env = 'development'; config.port = 3000; module.exports = config;
-
Once you have all the config transforms setup, make sure to update your package.json file to use the cross-env package I mentioned in Step 2 above. You will have to tell cross-env to set NODE_ENV to appropriate environment like so:
"scripts": { "start-local": "cross-env NODE_ENV=local node ./index.js", // NOTE: using a bundled file below as this is going to dev environment "start-dev": "cross-env NODE_ENV=development node ./dist/app.bundle.js" }