106

I have some things for development - e.g mocks which I would like to not bloat my distributed build file with.

In RequireJS you can pass a config in a plugin file and conditonally require things in based on that.

For webpack there doesn't seem to be a way of doing this. Firstly to create a runtime config for an environment I have used resolve.alias to repoint a require depending on the environment, e.g:

// All settings.
var all = {
    fish: 'salmon'
};

// `envsettings` is an alias resolved at build time.
module.exports = Object.assign(all, require('envsettings'));

Then when creating the webpack config I can dynamically assign which file envsettings points to (i.e. webpackConfig.resolve.alias.envsettings = './' + env).

However I would like to do something like:

if (settings.mock) {
    // Short-circuit ajax calls.
    // Require in all the mock modules.
}

But obviously I don't want to build in those mock files if the environment isn't mock.

I could possibly manually repoint all those requires to a stub file using resolve.alias again - but is there a way that feels less hacky?

Any ideas how I can do that? Thanks.

Dominic
  • 62,658
  • 20
  • 139
  • 163
  • Note that for now I have used alias's to point to an empty (stub) file on environments I don't want (e.g. require('mocks') will point to an empty file on non-mock envs. Seems a little hacky but it works. – Dominic Mar 10 '15 at 10:24

10 Answers10

64

You can use the define plugin.

I use it by doing something as simple as this in your webpack build file where env is the path to a file that exports an object of settings:

// Webpack build config
plugins: [
    new webpack.DefinePlugin({
        ENV: require(path.join(__dirname, './path-to-env-files/', env))
    })
]

// Settings file located at `path-to-env-files/dev.js`
module.exports = { debug: true };

and then this in your code

if (ENV.debug) {
    console.log('Yo!');
}

It will strip this code out of your build file if the condition is false. You can see a working Webpack build example here.

Matt Derrick
  • 5,674
  • 2
  • 36
  • 52
  • I'm a little confused by this solution. It doesn't mention how I'm supposed to set `env`. Looking through that example it seems as though they're handling that flag via gulp and yargs which not everyone is using. – a_dreb Apr 14 '16 at 23:59
  • 1
    How does this work with linters? Do you have to manually define new global variables that are added in the Define plugin? – mark May 02 '16 at 05:21
  • 2
    @mark yes. Add something like `"globals": { "ENV": true }` to your .eslintrc – Matt Derrick May 02 '16 at 20:29
  • how would i access the ENV variable in a component? I tried the solution above but I still get the error that ENV is not defined – jasan Sep 09 '16 at 11:09
  • You should be able to access the ENV variable just fine. It does require you to re-run Webpack if you just added the `webpack.DefinePlugin` though... – Matt Derrick Sep 09 '16 at 12:53
  • If you want to pass your own variable, you can do this via `var foo = "bar"; ... webpack.DefinePlugin({ENV: JSON.stringify(foo)}) ...`. – sibbl Nov 01 '16 at 17:11
  • You should use `JSON.stringify` on all of the defined values. Webpack inserts them 'as-is'. See here: https://github.com/webpack/docs/wiki/list-of-plugins#defineplugin. It should be rather: `ENV: JSON.stringify(require(path.join(__dirname, './path-to-env-files/', env)))` – pinkeen Jan 23 '17 at 13:01
  • 27
    It does NOT strip the code out of the build files ! I tested it and the code is here. – Lionel Mar 02 '17 at 15:42
  • @Lionel use https://babeljs.io/docs/plugins/minify-dead-code-elimination/ if you want to strip out the code. – Tom Roggero Nov 09 '17 at 01:42
55

Not sure why the "webpack.DefinePlugin" answer is the top one everywhere for defining Environment based imports/requires.

The problem with that approach is that you are still delivering all those modules to the client -> check with webpack-bundle-analyezer for instance. And not reducing your bundle.js's size at all :)

So what really works well and much more logical is: NormalModuleReplacementPlugin

So rather than do a on_client conditional require -> just not include not needed files to the bundle in the first place

Hope that helps

nml
  • 558
  • 4
  • 5
  • Nice didn't know about that plugin! – Dominic Jul 09 '17 at 12:01
  • With this scenario wouldn't you have multiple builds per environment? For example if I have web service address for dev/QA/UAT/production environments I would then need 4 separate containers, 1 for each environment. Ideally you would have one container and launch it with an environment variable to specify which config to load. – Brett Mathe Sep 13 '17 at 11:38
  • No, not really. That's exactly what you do with the plugin -> you specify your environment through env vars and it builds only one container, but for particular environment without redundant inclusions. Off course that also depends on how you setup your webpack config and obviously you can build all the builds, but it's not what this plugin is about and does. – nml Sep 20 '17 at 03:18
  • @RomanZhyliov What if I need to import a npm package based on client side errors. I think this plugin won't work, right? – Nevin Madhukar K Sep 22 '21 at 09:34
51

Use ifdef-loader. In your source files you can do stuff like

/// #if ENV === 'production'
console.log('production!');
/// #endif

The relevant webpack configuration is

const preprocessor = {
  ENV: process.env.NODE_ENV || 'development',
};

const ifdef_query = require('querystring').encode({ json: JSON.stringify(preprocessor) });

const config = {
  // ...
  module: {
    rules: [
      // ...
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: `ifdef-loader?${ifdef_query}`,
        },
      },
    ],
  },
  // ...
};
May Oakes
  • 4,359
  • 5
  • 44
  • 51
  • 4
    I upvoted this answer since the accepted answer does not strip out code as expected and the preprocessor-like syntax is more likely to be identified as a conditional element. – Christian Ivicevic Apr 20 '18 at 13:29
  • 1
    Thanks so much! It works like a charm. Several hours of experiments with ContextReplacementPlugin, NormalModuleReplacementPlugin, and other stuff – all failed. And here is ifdef-loader, saving my day. – jeron-diovis Dec 10 '18 at 14:41
30

I ended up using something similar to Matt Derrick' Answer, but was worried about two points:

  1. The complete config is injected every time I use ENV (Which is bad for large configs).
  2. I have to define multiple entry points because require(env) points to different files.

What I came up with is a simple composer which builds a config object and injects it to a config module.
Here is the file structure, Iam using for this:

config/
 └── main.js
 └── dev.js
 └── production.js
src/
 └── app.js
 └── config.js
 └── ...
webpack.config.js

The main.js holds all default config stuff:

// main.js
const mainConfig = {
  apiEndPoint: 'https://api.example.com',
  ...
}

module.exports = mainConfig;

The dev.js and production.js only hold config stuff which overrides the main config:

// dev.js
const devConfig = {
  apiEndPoint: 'http://localhost:4000'
}

module.exports = devConfig;

The important part is the webpack.config.js which composes the config and uses the DefinePlugin to generate a environment variable __APP_CONFIG__ which holds the composed config object:

const argv = require('yargs').argv;
const _ = require('lodash');
const webpack = require('webpack');

// Import all app configs
const appConfig = require('./config/main');
const appConfigDev = require('./config/dev');
const appConfigProduction = require('./config/production');

const ENV = argv.env || 'dev';

function composeConfig(env) {
  if (env === 'dev') {
    return _.merge({}, appConfig, appConfigDev);
  }

  if (env === 'production') {
    return _.merge({}, appConfig, appConfigProduction);
  }
}

// Webpack config object
module.exports = {
  entry: './src/app.js',
  ...
  plugins: [
    new webpack.DefinePlugin({
      __APP_CONFIG__: JSON.stringify(composeConfig(ENV))
    })
  ]
};

The last step is now the config.js, it looks like this (Using es6 import export syntax here because its under webpack):

const config = __APP_CONFIG__;

export default config;

In your app.js you could now use import config from './config'; to get the config object.

Community
  • 1
  • 1
ofhouse
  • 3,047
  • 1
  • 36
  • 42
18

another way is using a JS file as a proxy, and let that file load the module of interest in commonjs, and export it as es2015 module, like this:

// file: myModule.dev.js
module.exports = "this is in dev"

// file: myModule.prod.js
module.exports = "this is in prod"

// file: myModule.js
let loadedModule
if(WEBPACK_IS_DEVELOPMENT){
    loadedModule = require('./myModule.dev.js')
}else{
    loadedModule = require('./myModule.prod.js')
}

export const myString = loadedModule

Then you can use ES2015 module in your app normally:

// myApp.js
import { myString } from './store/myModule.js'
myString // <- "this is in dev"
Alejandro Silva
  • 8,808
  • 1
  • 35
  • 29
  • 20
    The only problem with if/else and require is that both required files will be bundled into the generated file. I haven't found a workaround. Essentially bundling happens first, then mangling. – alex Apr 12 '16 at 18:02
  • 2
    that's not necesary true, if you use in your webpack file the plugin `webpack.optimize.UglifyJsPlugin()`, the optimization of webpack won't load the module, as the line code inside the conditional is always false, so webpack remove it from the generated bundle – Alejandro Silva Apr 13 '16 at 12:23
  • @AlejandroSilva do you have a repo example of this? – Capuchin Jul 15 '16 at 08:47
  • 1
    @thevangelist yep: https://github.com/AlejandroSilva/mototracker/blob/master/webpack.config.prod.js it's a node+react+redux pet proyect :P – Alejandro Silva Jul 16 '16 at 23:15
4

Faced with the same problem as the OP and required, because of licensing, not to include certain code in certain builds, I adopted the webpack-conditional-loader as follows:

In my build command I set an environment variable appropriately for my build. For example 'demo' in package.json:

...
  "scripts": {
    ...
    "buildDemo": "./node_modules/.bin/webpack --config webpack.config/demo.js --env.demo --progress --colors",
...

The confusing bit that is missing from the documentation I read is that I have to make this visible throughout the build processing by ensuring my env variable gets injected into the process global thus in my webpack.config/demo.js:

/* The demo includes project/reports action to access placeholder graphs.
This is achieved by using the webpack-conditional-loader process.env.demo === true
 */

const config = require('./production.js');
config.optimization = {...(config.optimization || {}), minimize: false};

module.exports = env => {
  process.env = {...(process.env || {}), ...env};
  return config};

With this in place, I can conditionally exclude anything, ensuring that any related code is properly shaken out of the resulting JavaScript. For example in my routes.js the demo content is kept out of other builds thus:

...
// #if process.env.demo
import Reports from 'components/model/project/reports';
// #endif
...
const routeMap = [
  ...
  // #if process.env.demo
  {path: "/project/reports/:id", component: Reports},
  // #endif
...

This works with webpack 4.29.6.

Paul Whipp
  • 16,028
  • 4
  • 42
  • 54
1

I've struggled with setting env in my webpack configs. What I usually want is to set env so that it can be reached inside webpack.config.js, postcss.config.js and inside the entry point application itself (index.js usually). I hope that my findings can help someone.

The solution that I've come up with is to pass in --env production or --env development, and then set mode inside webpack.config.js. However, that doesn't help me with making env accessible where I want it (see above), so I also need to set process.env.NODE_ENV explicitly, as recommended here. Most relevant part that I have in webpack.config.js follow below.

...
module.exports = mode => {
  process.env.NODE_ENV = mode;

  if (mode === "production") {
    return merge(commonConfig, productionConfig, { mode });
  }
  return merge(commonConfig, developmentConfig, { mode });
};
Max
  • 488
  • 8
  • 19
0

Use envirnment variables to create dev and prod deployments:

https://webpack.js.org/guides/environment-variables/

Simon H
  • 508
  • 1
  • 5
  • 18
0

I use string-replace-loader to get rid of an unnecessary import from the production build, and it works as expected: the bundle size becomes less, and a module for development purposes (redux-logger) is completely removed from it. Here is the simplified code:

  • In the file webpack.config.js:
rules: [
  // ... ,
  !env.dev && {
    test: /src\/store\/index\.js$/,
    loader: 'string-replace-loader',
    options: {
      search: /import.+createLogger.+from.+redux-logger.+;/,
      replace: 'const createLogger = null;',
    }
  }
].filter(Boolean)
  • In the file src/store/index.js:
// in prod this import declaration is substituted by `const createLogger = null`:
import { createLogger } from 'redux-logger';
// ...
export const store = configureStore({
  reducer: persistedReducer,
  middleware: createLogger ? [createLogger()] : [],
  devTools: !!createLogger
});
Roman Karagodin
  • 740
  • 2
  • 11
  • 16
-2

While this is not the best solution, it may work for some of your needs. If you want to run different code in node and browser using this worked for me:

if (typeof window !== 'undefined') 
    return
}
//run node only code now
Esqarrouth
  • 38,543
  • 21
  • 161
  • 168