variable config file based on environment - reactjs, webpack

1.5k views Asked by At

I need bunch of global variables in my reactjs components(example: hostnames, token, api urls, etc) based on the environment. but I don't want to add it to the js individually. I would like to create project.config file to set up prod:{hostname:example.com, api-url:prod, etc} and dev:{hostname:localhost.com, api-url:dev, etc}, I installed loose-envify, but I have to specify for each var.

var path = require('path');
var webpack = require('webpack');
var ExtractTextPlugin = require("extract-text-webpack-plugin");

module.exports = {
  devtool: 'eval',
  entry: [
    'webpack-dev-server/client?http://example.com:3000',
    'webpack/hot/only-dev-server',
    './src/index'
  ],
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle.js',
    publicPath: '/static/'
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.DefinePlugin({'process.env.NODE_ENV': JSON.stringify('production')}),
    new ExtractTextPlugin("static/super.css", {
            allChunks: true
        })
  ],
  module: {
    loaders: [{
      test: /\.js$/,
      loaders: ['react-hot', 'babel'],
      include: path.join(__dirname, 'src')
    },
    {  test: /\.scss$/,
        loaders: ["style", "css", "sass"],
        include: path.join(__dirname, 'src')
    }
    ]
  }
};
2

There are 2 answers

0
Harkirat Saluja On

I was trying to try something similar and tried following which seems to work fine.

In your webpack config add a DefinePlugin. Following is my webconfig:-

 plugins: [
    new BundleTracker({filename: './webpack-stats.json'}),
    new webpack.DefinePlugin({
    'process.env': {
      'NODE_ENV': JSON.stringify(process.env.environment),
    }
  })
  ],

Now while compiling use the following commands:-

environment=local webpack (for local)
environment=development webpack(for dev)
environment=production webpack(for prod)

Now if you see I have set 'NODE_ENV' with the cli input so when 'NODE_ENV' is production as value, the webpack automatically minifies your output bundle.

Now say you have API url declared in a file(I had Constants.jsx), so I added following to constants.jsx. So basically you can read the NODE_ENV set in webpack config in this Constants.jsx and import them in your components from where APIS are called by exporting it from here.

const api_url=function(){
  let api_url='';
  if(process.env.NODE_ENV == 'local'){
    api_url= 'http://localhost:8002/api/v0';
  }
  else if(process.env.NODE_ENV == 'development'){
    api_url = 'https://development/api/v0';
  }
  else if(process.env.NODE_ENV == 'production'){
    api_url = 'https://production/api/v0';
  }
  return api_url;
}

export const url= api_url();

Hope it helped!

0
Michael Rasoahaingo On

Did you try to stringify a config json that can have some common and overridden properties for dev or prod? Which will be given to the new webpack.DefinePlugin({...})?