Estus Flask
Estus Flask

Reputation: 222319

Dynamic require in Webpack at build time

Considering there's Webpack config

...
entry: {
    'bundle-with-dependency-a': 'common-entry.js',
    'bundle-with-dependency-b': 'common-entry.js'
},
resolve: {
    alias: {
        'dep-a': ...,
        'dep-b': ...
    },
},

and I would expect in common-entry.js something like this:

require('dep-' + entryName.slice(-1));

I.e. I want to provide the definition for particular require from config.

The problem is that there may be more than 2 dependency options, I avoid copypasting. And I'm about to do this at build time, instead of requiring the chunks with JSONP.

How can this require be made dynamic?

The only option I've got here is to have different configuration for each dep, but this requires to make multiple Webpack passes instead of single. Not very convenient.

Upvotes: 15

Views: 1885

Answers (1)

Alexandre Kirszenberg
Alexandre Kirszenberg

Reputation: 36408

Using the imports-loader:

webpack.config.js

{
  entry: {
    'bundle-with-dependency-a': 'imports?depName=>"dep-a"!./common-entry.js',
    'bundle-with-dependency-b': 'imports?depName=>"dep-b"!./common-entry.js',
  },
  // ...
}

The depName variable will then be exposed to the common-entry.js module.

Upvotes: 6

Related Questions