I ended up using something similar to Matt Derrickโs Answer , but was worried about two things:
- The full configuration is introduced every time I use
ENV (which is bad for large configs). - I have to define several entry points because
require(env) points to different files.
I came up with a simple composer that creates a configuration object and injects it into the configuration module.
Here is the file structure that I use for this:
config/ โโโ main.js โโโ dev.js โโโ production.js src/ โโโ app.js โโโ config.js โโโ ... webpack.config.js
main.js contains all the default settings:
// main.js const mainConfig = { apiEndPoint: 'https://api.example.com', ... } module.exports = mainConfig;
Only dev.js configurations are stored in dev.js and production.js , which override the main configuration:
// dev.js const devConfig = { apiEndPoint: 'http://localhost:4000' } module.exports = devConfig;
The important part is webpack.config.js which compiles the configuration and uses DefinePlugin to generate the __APP_CONFIG__ environment __APP_CONFIG__ which contains the compiled configuration object:
const argv = require('yargs').argv; const _ = require('lodash'); const webpack = require('webpack'); // Import all app configs const appConfig = require('./config/main'); const appConfigDev = require('./config/dev'); const appConfigProduction = require('./config/production'); const ENV = argv.env || 'dev'; function composeConfig(env) { if (env === 'dev') { return _.merge({}, appConfig, appConfigDev); } if (env === 'production') { return _.merge({}, appConfig, appConfigProduction); } } // Webpack config object module.exports = { entry: './src/app.js', ... plugins: [ new webpack.DefinePlugin({ __APP_CONFIG__: JSON.stringify(composeConfig(ENV)) }) ] };
The last step now is config.js , it looks like this (es6 export-import syntax is used here because it is in webpack):
const config = __APP_CONFIG__; export default config;
In your app.js you can now use import config from './config'; to get the configuration object.
ofhouse Apr 16 '17 at 10:29 on 2017-04-16 10:29
source share