2

I have a project compiled with webpack. There are separate dev & production builds, differentiated by the NODE_ENV environment variable. For the dev build, another env variable is required: REPO_PATH.

Is there a way within webpack to check for the presence or absence of REPO_PATH, throw a custom error and kill the build if it is not set?

My current solution relies of package.json scripts:

package.json

{
  ...
  "scripts": {
    "dev": "if test -z $REPO_PATH; then echo \"Please set REPO_PATH"; exit 0; fi && NODE_ENV=development webpack --progress --hide-modules"
  }
}

This works, but isn't ideal, since some of our developers use windows machines and the if/then statement above is specific to unix systems.

It also just seems like something that should be possible with a small plugin or something similar, but I don't know what I'm looking for.

ebbishop
  • 1,833
  • 2
  • 20
  • 45

1 Answers1

0

The best solution I've come up with so far is writing a simple webpack plugin that checks for the existence of each environment variables listed, and throws an error if any are missing.

var externalDevLibraries = [
  'VARIABLE_1_NAME',
  'VARIABLE_2_NAME',
];


class EnvCheckerPlugin {

  apply(compiler) {
    compiler.plugin("environment", function (compilation, callback) {
      console.log('Checking for necessary env variables...')

      var missingEnvVars = [];
      for (let i = 0, l = devEnvVars.length; i < l; i ++) {
        var env = devEnvVars[i];
        if (!process.env[env]) {
          missingEnvVars.push(env);
        }
      }

      if (missingEnvVars.length) {
        console.error(chalk.yellow("Please set the following env variables.\nThen, try re-running the dev build."));
        console.error(chalk.red(`  - ${missingEnvVars.join('\n  * ')}`));
        throw new Error('Missing env variables. Please see additional logging above');
      }
    });
  }
};

This plugin is used only when NODE_ENV=development, as follows:

if (process.env.NODE_ENV === 'development') {
  // ... other dev-specific stuff

  module.exports.plugins = (module.exports.plugins || []).concat([
      // other dev-specific plugins... 
      new EnvCheckerPlugin(),
  ]);

}
ebbishop
  • 1,833
  • 2
  • 20
  • 45