14

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.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565

1 Answers1

6

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.

Alexandre Kirszenberg
  • 35,938
  • 10
  • 88
  • 72
  • It looks good, I'm not sure that I even knew that loaders can be used in entries. I wonder if there are ways other than 'imports', there can be several deps with same ('a' or 'b') prefix which will make loader query string quite long. – Estus Flask Oct 25 '15 at 15:20
  • Then I'd recommend either looking at making your own loader, or creating a function that generates the query string for you. An example: `imports({ depName: 'dep-a' }) + './common-entry.js'` – Alexandre Kirszenberg Oct 25 '15 at 15:40
  • Yes, constructing query is good enough. I wonder if there are other roundabouts, e.g. `context` and ContextReplacementPlugin (Webpack documentation is ridiculously lacking on their potential use). – Estus Flask Oct 27 '15 at 11:28