Rogier
Rogier

Reputation: 152

Use env variable as alias in webpack config

I have a use case to have a different Webpack alias on an environment variable.

In this case process.env.MY_ENV_VARIABLE returns undefined during the webpack build, while returning my set variable in the application itself.

Webpack config would have something like this:

resolve: {
    alias: {
      '@my_path': path.resolve(__dirname, `src/${ENV.MY_ENV_VARIABLE}`),
    }
},

NOTE: I can find many solutions for making your .env variables available in your final application, but nothing useful to use it in your webpack config itself...

Upvotes: 1

Views: 938

Answers (1)

Rogier
Rogier

Reputation: 152

Working answer copied from an answer by @nickbullock on this question :

Add this to the top of your webpack config (build in some checks if necessary):

const DotEnv = require('dotenv').config({path: __dirname + '/.env'});

const variableFromEnv = () => {
  return DotEnv.parsed['MY_ENV_VARIABLE'];
};

Than call your funtion to return your variable in the config object:

resolve: {
    alias: {
      '@my_path': path.resolve(__dirname, `src/${variableFromEnv()}`),
    }
},

Upvotes: 1

Related Questions