8

So I want to do:

if (process.env.NODE_ENV === 'production') {
  import StatsPlugin from 'webpack-stats-plugin';
}

But eslint says:

Parsing error: 'import' and 'export' may only appear at the top level

I'm using babel-eslint parser.

Does this imply I can't load modules conditionally?

loganfsmyth
  • 156,129
  • 30
  • 331
  • 251
Sid Jain
  • 177
  • 1
  • 11

1 Answers1

5

Dynamic synchronous imports are not possible with ES2015 modules. It's only possible to import stuff dynamically with asynchronous imports via import().

Why don't you just import it and apply it conditionally?

import StatsPlugin from 'webpack-stats-plugin';

...

if (process.env.NODE_ENV === 'production') {
  config.plugins.push(new Statsplugin())
}
Johannes Ewald
  • 17,665
  • 5
  • 44
  • 39
  • If I import a module and don't refer to it anywhere in my code later (i.e. essentially include but not use), does webpack still include it in the bundle? – Sid Jain Jun 04 '16 at 00:50
  • 7
    webpack 1 will still include it because CommonJS don't allow this kind of optimization, webpack 2 can remove unused functions when ES2015 modules are used. This feature is called tree-shaking. – Johannes Ewald Jun 05 '16 at 22:58
  • 1
    @jhnns Can you include that comment in your answer? I was driven here by a similar situation, but it seems that with Webpack 2 the optimization is already being made. – E_net4 Oct 17 '16 at 10:21
  • @jhnns is there any way webpack 1 can exclude `require`d modules inside a conditional like `if (process.env.NODE_ENV === 'production') { config.plugins.push(new require('webpack-stats-plugin')()) }`? Seems like it would be possible... – Andy Oct 29 '16 at 00:00
  • When you write `if (PRODUCTION)` you can use the `DefinePlugin` to replace all occurrences of `PRODUCTION` into `false`. Webpack will not follow `require()` inside of dead code branches. Unfortunately, `if ("production" === "production") {` is currently not detected as dead code branch – Johannes Ewald Nov 04 '16 at 14:39
  • This is really getting to be a problem with isomorphic JS. Sometimes you need to conditionally use deps on the server that will break the webpack build for the client. – Andy Dec 13 '16 at 00:41
  • This is what `resolve.alias` is fixing in webpack. Furthermore, if you write small separate modules with their own `package.json`, you can use [the `browser` field](https://gist.github.com/defunctzombie/4339901) in order to switch entry points in your module. – Johannes Ewald Dec 14 '16 at 09:47