Webpack requires many requirements (dynamic line required)

I would like to require a list of requirements in webpack. As soon as I replace the string parameter of the require function with a variable or constant, it can no longer make this requirement.

Here is a great working example:

const angular = require('angular'); 

But as soon as I change this to the following, it no longer works:

 const angularString = 'angular'; const angular = require(angularString); 

My goal is to have a static list of dependencies and introduce them one by one, for example:

 const angularDependencies = [ 'angular-socket-io', 'angular-ui-router' ]; for(var i = 0; i < angularDependencies.length; i++) { require(angularDependencies[i]); } 

This is the error message I received:

 WARNING in ./app/app.js Critical dependencies: 14:1-14 the request of a dependency is an expression @ ./app/app.js 14:1-14 WARNING in ./app ^\.\/.*$ Module not found: Error: a dependency to an entry point is not allowed @ ./app ^\.\/.*$ WARNING in ./app ^\.\/.*$ Module not found: Error: a dependency to an entry point is not allowed @ ./app ^\.\/.*$ 
+6
source share
3 answers

This will not work, as WebPack is a build tool that analyzes the source files to train what to include. It does not run your code to see what it does. This means that your code can only include lines inside the require statement.

If you want to write your code this way, look at SystemJS instead of WebPack.

https://github.com/systemjs/systemjs

+4
source

Webpack supports dynamic needs, but you need to say how to find files using contexts . You can try something like this before requiring your modules:

 var req = require.context(".", true, /^angular-.+$/) req("angular-thing") 

If something like this does not work, you will need to use a different approach in your code, because WebPack needs to know which modules to include in your package at compile time.

+4
source

Create angularDependencies.js :

 module.exports = [ 'angular-socket-io', 'angular-ui-router' ]; 

Then add it to the webpack.config.js section. It should look like this:

 require('./src/angularDependencies').concat(['./myApp.js']) 
+2
source

All Articles