I have some code where I have placeholders. There are some variables that I don't know yet that I need to fill in when the code is pushed to production. Right now I have the following in a file called constants.js.
export const PublicAddress = process.env.PUBLIC_ADDRESS || console.error( "Public address is not yet set." );
This code works just fine and there will be an error logged to the console when PUBLIC_ADDRESS is empty.
However, if PUBLIC_ADDRESS was empty AND I forgot to hardcode another value, I'd like Webpack to throw an error when compiling instead. It's really important that I don't forget to put in a real value when I compile it for production.
Is that possible?
It's typically this kind of check that you can provide in your own webpack plugin. here is a basic implementation of a custom plugin that check if all string from an array refer to an env variable :
class EnvVarExistPlugin {
apply(compiler) {
const envsVarToCheck = ['TEST_VAR', 'TEST_VAR2'] // put your env var list here
envsVarToCheck.forEach(envVar => {
if (!!!process.env[envVar]) {
throw new Error(`Environment variable : ${envVar} is missing`);
}
});
}
};
module.exports = EnvVarExistPlugin
Then register your plugin in your webpack.config.js :
const { resolve } = require("path");
const EnvVarExistPlugin = require("./pathToYourPlugin");
require('dotenv').config({ path: './.env' }); // adapt path to your env file
module.exports = {
entry: resolve(__dirname, "src/index.js"),
mode: 'development',
output: {
path: resolve(__dirname, "dist"),
filename: "bundle.js"
},
plugins: [new EnvVarExistPlugin()]
};