Q:

Webpack swap function implementation at build time

I am trying to create a component library with React and I need 2 different implementations of a decorator function depending on the build target.
import { decorator } from 'decorator';
const reactComponent = () => (<p>I am a React component.</p>)
export default decorator(reactComponent);

I would like to have 2 builds: 1 with the default decorator implementation and another build with a different implementation.

A:

You have to pass ENV to webpack config, IE:

"bulid:prod": cross-env NODE_ENV=production webpack [...options and parameters]

then in webpack

plugins: [
// [...plugins],
new webpack.DefinePlugin({
      process: {
        env: {
          NODE_ENV: JSON.stringify(process.env.NODE_ENV),
        },
      },
    }),
// [...plugins]
]

then in your code:

switch(process.env.NODE_ENV) { 
  case "production": { 
     // ...do things
     break; 
  } 
  case "staging": { 
     // ...do things
     break; 
  }
  case "test": { 
     // ...do things 
     break;    
  } 
  default: { 
     console.log("Invalid choice"); 
     break;              
  } 
} 

