How to run custom config file in node.js project - javascript

In a node.js project using express framework, usually config folder has 3 files:
config.json - runs in prod env
development.json - runs in dev env
staging.json - runs in stage env
I want to create another config file called example.json and run local dev environment using example.json instead of development.json when ever the code is run with a special environment variable process.env.LOCAL_PROD.
Is there a way to do this?

You can do this with node-config and I highly recommend it as it allows for multiple config files and even hostname based config files. It also supports multiple formats including .js configs not just .json, you can read more about the various setups for configuration files in the node-config wiki. I use it in almost all of my applications that require some configuration due to how easy it is to use.
Now if you don't want to use a package to handle this, then you can do it with just using require() since it can read and parse .json files as well as .js. The common environment variable to use when setting what environment the application is running within is named NODE_ENV.
let config
let env = process.env.NODE_ENV.toLowerCase()
if (env === 'production') {
config = require('./config.json')
} else if (env === 'staging') {
config = require('./staging.json')
} else if (env === 'dev') {
config = require('./development.json')
} else {
console.log('No configurable NODE_ENV detected, no config loaded')
}

Related

Variables in .env file is not updated. How to reset

Im building an app with Quasar (vue) where I am using .env file to store my keys to the database. I was going to switch to another instance but after I changed the keys in the env file it still calls the old values of the variables. They seemd to be cached in some way.
Im using dotenv to call the env file.
I have tried of course to reset the history in browser as well as running
npm cache clean --force
How can I reset the env files?
Quasar handles env variables through quasar.config.js file, not separate .env files. See the documentation.
quasar.config.js
module.exports = function (ctx) {
return {
// ...
build: {
// passing down to UI code from quasar.config.js
env: {
API: ctx.dev
? 'https://dev.api.com'
: 'https://prod.api.com'
}
}
}
}
As noted in the docs, if you do want to use .env files you'll have to add the dotenv package to your project and point quasar.config.js to use the env variables set with dotenv
build: {
env: require('dotenv').config().parsed
}

Quasar - Support multiple environments

I’m trying to create project with multiple environments: staging, prod, test + development obviously.
With Vuejs that’s pretty straightforward
vue-cli-service build --mode staging
And create .env.staging file.
Important note that process.env should be accessed from quasar.conf file in order to set different publicPath for each env.
How can I achieve this behavior at Quasar?
Thanks
Check out the #quasar/qenv extension it seems to support multiple environments. https://github.com/quasarframework/app-extension-qenv
Another approach, as I am using Firebase Hosting and both staging and production hosting is in the same project ... I had the idea of using quasar build -d (debug mode) as staging and quasar build as production, each with its own dist folder, and I set a DEPLOY_MODE env variable in quasar.conf.js accordingly:
build: {
distDir: ctx.debug ? `dist/${ctx.modeName}-dev` : `dist/${ctx.modeName}`,
env: {
DEPLOY_MODE: ctx.prod && !ctx.debug ? 'PRODUCTION' : (ctx.prod && ctx.debug ? 'STAGING' : 'DEV')
},
...
I used the dotenv extension and have an .env.prod and .env.dev file. Within .env.prod I define the production and staging specific keys, e.g. API_KEY=blah, API_STAGING_KEY=blah, then in my boot file, I use process.env.DEPLOY_MODE to determine which keys to use in my
production env file.
if(process.env.DEPLOY_MODE === 'staging') {
const API_KEY = process.env.API_STAGING_KEY
} else {
const API_KEY = process.env.API_KEY
}
I suspect #qenv is more elegant but this was enough for my simple project.

How to exclude code from production in build-time?

How do I exclude typescript code from webpack bundle during build-time?
For example, I have this line of code in app.ts (nodejs application):
const thisShouldNotBeInProductionBundleJustInDevBundle = 'aaaaaaa';
I want when I build my app using webpack configuration to exclude this code.
In webpack version 4 you are able to set mode: 'production' in your webpack config. (https://webpack.js.org/concepts/mode/)
So in your source code you can use the following:
if (process.env.NODE_ENV === 'development') {
const thisShouldNotBeInProductionBundleJustInDevBundle = 'aaaaaaa';
...
}
In conclusion all code inside if and ifs themself will be automatically removed during building your bundle
Webpack has a mode setting, which allows you to switch between development and production builds.
In your code you can use process.env.NODE_ENV to find out wether you are in production or not, Webpack uses that property to eliminate "production dead code":
// declare variable everywhere to prevent unresolvable variable references
let onlyInDev = "";
// The following should be shaken away by webpack
if(process.env.NODE_ENV === "development") {
onlyInDev = "test";
}
If the value is a sensitive information that should not be leaked to your production build, I would search for it in the bundle to make sure that it doesn't get leaked if the building pipeline changes.

Conditional javascript source code

Background:
I have 3 different URLs, one per environment (dev, test, prod), and I don't want to expose all the URLs in the client (source code).
How can I expose in the client code, just the one corresponding to the environment in context?
Note: As I understand, I need to do something in the build process using environment variables (I'm using node.js). However, I don't want to touch anything related with webpack, as what I'm trying to do is a standalone package that can be imported in any application regardless of the framework they are using. Webpack plugins/configuration are not an option, but I can use any npm package if required.
During your build process, you can check the environment variable and then copy over a config file. For example, you could keep your URIs in /config/<env>.js, and then copy/rename it to /settings.js during the build. Your URL could be exported from that.
The following npm package fits my requirements completely https://www.npmjs.com/package/config , you can load conditional files based on the node environment variable NODE_ENV, so when NODE_ENV=development, the file /config/development.js is used to create the build. you can use different extensions for the config files, also you can customize the config folder path by changing the environment variable $NODE_CONFIG_DIR heres an example:
const config = require('config');
process.env.$NODE_CONFIG_DIR = './' // relative path ./config
const url = config.get('url');
//if NODE_ENV is development will load the file config/development.js
console.log(url);

How to manage configuration for Webpack/Electron app?

I am using Webpack 2 and Electron to build nodejs application on Mac.
In my project in the root I have directory 'data' where I store configuration in a json like data/configurations/files.json (in practices there are different files with dynamic names)
After webpackaing though when I call: fs.readdirSync(remote.app.getAppPath()); to get files in the root I get only these packed: [ "default_app.js", "icon.png", "index.html", "main.js", "package.json", "renderer.js" ]
path.join(remote.app.getAppPath(), 'data/tests/groups.json'); called with FS ReadSync leads to an issue Error: ENOENT, data/tests/groups.json not found in /Users/myuser/myproject/node_modules/electron/dist/Electron.‌​app/Contents/Resourc‌​es/default_app.asar. So it seems that the whole data folder is not picked up by webpacker.
Webpack config is using json-loader and I did not find any documentation mentioning anything special about including specific files or jsons. Or do I have to reference json files in my code differently as they might be packed under main.js.
What is the best practice for Electron/Webpack for managing JSON config files? Am I doing something wrong when webpacking the project?
My project is based of https://github.com/SimulatedGREG/electron-vue using webpack/electron/vue
The Webpack Misconception
One thing to understand upfront is that webpack does not bundle files required through fs or other modules that ask for a path to a file. These type of assets are commonly labeled as Static Assets, as they are not bundled in any way. webpack will only bundle files that are required or imported (ES6). Furthermore, depending on your webpack configuration, your project root may not always match what is output within your production builds.
Based on the electron-vue documentation's Project Structure/File Tree, you will find that only webpack bundles and the static/ directory are made available in production builds. electron-vue also has a handy __static global variable that can provide a path to that static/ folder within both development and production. You can use this variable similar to how one would with __dirname and path.join to access your JSON files, or really any files.
A Solution to Static Assets
It seems the current version of the electron-vue boilerplate already has this solved for you, but I'm going to describe how this is setup with webpack as it can apply to not only JSON files and how it can also apply for any webpack + electron setup. The following solution assumes your webpack build outputs to a separate folder, which we'll use dist/ in this case, assumes your webpack configuration is located in your project's root directory, and assumes process.env.NODE_ENV is set to development during development.
The static/ directory
During development we need a place to store our static assets, so let's place them in a directory called static/. Here we can put files, such as JSONs, that we know we will need to read with fs or some other module that requires a full path to the file.
Now we need to make that static/ assets directory available in production builds.
But webpack isn't handling this folder at all, what can we do?
Let's use the simple copy-webpack-plugin. Within our webpack configuration file we can add this plugin when building for production and configure it to copy the static/ folder into our dist/ folder.
new CopyWebpackPlugin([
{
from: path.join(__dirname, '/static'),
to: path.join(__dirname, '/dist/static'),
ignore: ['.*']
}
])
Okay so the assets are in production, but how do I get a path to this folder in both development and production?
Creating a global __static variable
What's the point of making this __static variable?
Using __dirname is not reliable in webpack + electron setups. During development __dirname could be in reference to a directory that exists in your src/ files. In production, since webpack bundles our src/ files into one script, that path you formed to get to static/ doesn't exist anymore. Furthermore, those files you put inside src/ that were not required or imported never make it to your production build.
When handling the project structure differences from development and production, trying to get a path to static/ will be highly annoying during development having to always check your process.env.NODE_ENV.
So let's simplify this by creating one source of truth.
Using the webpack.DefinePlugin we can set our __static variable only in development to yield a path that points to <projectRoot>/static/. Depending if you have multiple webpack configurations, you can apply this for both a main and renderer process configuration.
new webpack.DefinePlugin({
'__static': `"${path.join(__dirname, '/static').replace(/\\/g, '\\\\')}"`
})
In production, we need to set the __static variable manually in our code. Here's what we can do...
index.html (renderer process)
<!-- Set `__static` path to static files in production -->
<script>
if (process.env.NODE_ENV !== 'development') window.__static = require('path').join(__dirname, '/static').replace(/\\/g, '\\\\')
</script>
<!-- import webpack bundle -->
main.js (main process)
// Set `__static` path to static files in production
if (process.env.NODE_ENV !== 'development') {
global.__static = require('path').join(__dirname, '/static').replace(/\\/g, '\\\\')
}
// rest of application code below
Now start using your __static variable
Let's say we have a simple JSON file we need to read with fs, here's what we can accomplish now...
static/someFile.json
{"foo":"bar"}
someScript.js (renderer or main process)
import fs from 'fs'
import path from 'path'
const someFile = fs.readFileSync(path.join(__static, '/someFile.json'), 'utf8')
console.log(JSON.parse(someFile))
// => { foo: bar }
Conclusion
webpack was made to bundle assets together that are required or imported into one nice bundle. Assets referenced with fs or other modules that need a file path are considered Static Assets, and webpack does not directly handle these. Using copy-webpack-plugin and webpack.DefinePlugin we can setup a reliable __static variable that yields a path to our static/ assets directory in both development and production.
To end, I personally haven't seen any other webpack + electron boilerplates handle this situation as it isn't a very common situation, but I think we can all agree that having one source of truth to a static assets directory is a wonderful approach to alleviate developer fatigue.
I think the confusion, (if there is any), might come from the fact that webpack not only "packs", embeds, things, code, etc... but also process content with its plugins.
html plugin being a good example, as it simply generates an html file at build-time.
And how this relates to the config file issue?,
well depending on how you are "requiring" the "config" file, what plug-in you are using to process that content.
You could be embedding it, or simply loading it as text, from file system or http, or else...
In the case of a config file, that I guess you want it to be parsed at runtime,
otherwise it's just fancy hardcoding values that perhaps you could be better simply typing it in your source code as simple objects.
And again in that case I think webpack adds little to nothing to the runtime needs, as there is nothing to pre-pack to read at later use,
so I would possibly instead or "require"it, i'll read it from the file system, with something like :
// read it parse it relative to appPath/cwd,
const config = JSON.parse(
fs.readfileSync(
path.join( app.getAppPath(), "config.json" ),
"utf-8"
))
//note: look fs-extra, it does all that minus the app.path plus async
and electron will read it from the file system , or if using Electron.require will read it from asar|fileSystem (in that order if I remember correctly, I could be wrong),
Webpack design philosophy is focused around very simple yet powerful concept:
Transform and bundle everything that is actually used by your app.
To achieve that webpack introduces a powerful concept of dependency graph, which is able to manage virtually any kind of dependencies (not only *.js modules) by the means of so-called loaders.
The purpose of a loader is to transform your dependency in a way that makes statement import smth from 'your_dependency' meaningful. For instance, json-loader calls JSON.parse(...) during loading of *.json file and returns configuration object. Therefore, in order to take advantage of webpack dependency resolution system for managing JSONs, start from installing json-loader:
$ npm install --save-dev json-loader
Then modify your webpack.config.js in the following way:
module.exports = {
...
module: {
rules: [
{test: /\.json$/, use: 'json-loader'}
]
}
...
};
At this point webpack should be able to resolve your JSON dependencies by their absolute paths, so the following should work (I assume here that you have a subdirectory config of your root context dir, containing file sample.json):
import sampleCfg from './config/sample.json';
But importing physical paths doesn't lead to elegant, robust and maintainable code (think of testability, for example), so it is considered a good practice to add aliases to your webpack.config.js for abstracting away your physical .config/ folder from your import statements
module.exports = {
...
resolve: {
alias: {
cfg: './config'
}
}
...
}
Then you'll be able to import your JSON config like that:
import sampleCfg from 'cfg/sample.json'
Finally, if you use SimulatedGREG/electron-vue Electron project template (as you mentioned in your post), then you have three webpack configuration files:
.electron-vue/webpack.web.config.js - use this config file if you use this template just for ordinary web development (i.e. not for building native Electron projects);
.electron-vue/webpack.main.config.js - use this file to configure webpack module that will run inside Electron's main process;
.electron-vue/webpack.renderer.config.js - use this file for Electron's renderer process.
You can find more information on main and renderer processes in the official Electron documentation.

Categories

Resources