15

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.

1 Answer 1

6
+400

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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.
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'
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).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.