webpack dynamic module loader by require

You cannot use a variable as argument to require. Webpack needs to know what files to bundle at compile time. As it does no program flow analysis, it can't know what you pass to the function. In that case it might be obvious, but this could go as far as using user input to decide what module to require, and there is no way webpack can possibly know which modules to include at compile time, so webpack does not allow it.

The example you posted is a bit different. You could use require with a concatenated string. For example:

require(`./src/${moduleName}/test`);

Which modules does webpack need to include in the bundle? The variable moduleName could be anything, so the exact module is not known at compile time. Instead it includes all modules that could possibly match the above expression. Assuming the following directory structure:

src
├─ one
│   └─ test.js
├─ two
│   ├─ subdir
│   │   └─ test.js
│   └─ test.js
└─ three
    └─ test.js

All of these test.js files will be included in the bundle, because moduleName could be one or something nested like two/subdir.

For more details see require with expression of the official docs.

You cannot loop through an array and import every module of the array, with the above exception by concatenating a string, but that has the effect of including all possible modules and should generally be avoided.


I ran into this problem in an electron environment. My use case was being able to require dynamically created files in an IDE like application. I wanted to use the electron require, which is basically a NodeJS Common module loader. After some back and forth I landed on a solution that uses webpack's noParse module configuration.

First create a module that that will be ignored by webpack's parser:

// file: native-require.js
// webpack replaces calls to `require()` from within a bundle. This module
// is not parsed by webpack and exports the real `require`
// NOTE: since the module is unparsed, do not use es6 exports
module.exports = require

In my webpack config, under module, instruct the bundler not to parse this module:

{
  module: {
    noParse: /\/native-require.js$/,
  }
}

Lastly, in any bundle where you want to access the original require:

import nativeRequire from './native-require'
const someModule = nativeRequire('/some/module.js') // dynamic imports