Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic require in Webpack at build time

Tags:

webpack

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.

like image 593
Estus Flask Avatar asked Oct 19 '15 04:10

Estus Flask


1 Answers

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.

like image 61
Alexandre Kirszenberg Avatar answered Sep 19 '22 16:09

Alexandre Kirszenberg