3

I have a Webpacked TypeScript app that loads a json config file. The project is in its infancy so we don't have a good config store in production yet, so we're storing our config files side-by-side: config.json and config.dev.json.

In my TypeScript, I want to be able to type

import Config from './path/to/config.json';

and if --mode development is passed into webpack, I want it to require ./path/to/config.dev.json.

Is this possible with just Webpack or Webpack + tsconfig.json?

dx_over_dt
  • 13,240
  • 17
  • 54
  • 102

1 Answers1

4

The idea from the answer below is to use the webpack-define-plugin

webpack.config.js

const argv = require('yargs').argv;
const webpack = require('webpack');

// Import all app configs
const appConfig = require('./path/to/config.json'); /* Base config */
const appConfigDev = require('./path/to/config.dev.json'); /* Development */
const appConfigProd = require('./path/to/config.prod.json'); /* Production */

const ENV = argv.env || 'dev';

function composeConfig(env) { /* Helper function to dynamically set runtime config */
  if (env === 'dev') {
    return { ...appConfig, ...appConfigDev };
  }

  if (env === 'production') {
    return { ...appConfig, ...appConfigProd };
  }
}

// Webpack config object
module.exports = {
  entry: './src/app.js',
  ...
  plugins: [
    new webpack.DefinePlugin({
      __APP_CONFIG__: JSON.stringify(composeConfig(ENV))
    })
  ]
};

Usage in your application

const config = __APP_CONFIG__
/* config available in module scope */

Reference:

Peter
  • 2,796
  • 1
  • 17
  • 29