Build Toggles

It is common to switch in JavaScript projects based on where they are being run. You can do this quite easily with webpack as its supports dead code elimination based on environment variables.

Add different targets in your package.json scripts:

  1. "build:test": "webpack -p --config ./src/webpack.config.js",
  2. "build:prod": "webpack -p --define process.env.NODE_ENV='\"production\"' --config ./src/webpack.config.js",

Of course I am assuming you have npm install webpack --save-dev. Now you can run npm run build:test etc.

Using this variable is super easy as well:

  1. /**
  2. * This interface makes sure we don't miss adding a property to both `prod` and `test`
  3. */
  4. interface Config {
  5. someItem: string;
  6. }
  7. /**
  8. * We only export a single thing. The config.
  9. */
  10. export let config: Config;
  11. /**
  12. * `process.env.NODE_ENV` definition is driven from webpack
  13. *
  14. * The whole `else` block will be removed in the emitted JavaScript
  15. * for a production build
  16. */
  17. if (process.env.NODE_ENV === 'production') {
  18. config = {
  19. someItem: 'prod'
  20. }
  21. console.log('Running in prod');
  22. } else {
  23. config = {
  24. someItem: 'test'
  25. }
  26. console.log('Running in test');
  27. }

We use process.env.NODE_ENV just because it is conventional in a lot of JavaScript libraries themselves e.g. React.