Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Webpack require array of requirements (require dynamic string)

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 a constant, it cannot inject the requirement anymore.

Here is a perfectly working example:

const angular = require('angular');

But as soon as I change this to the following, it doesnt work anymore:

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

My goal is to have a static list of dependencies and inject them one by one, like this:

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 got:

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 ^\.\/.*$
like image 751
ssc-hrep3 Avatar asked Jun 04 '16 09:06

ssc-hrep3


1 Answers

That won't work as WebPack is a build tool that analyses you source files to workout what to include. It does not run your code to see what it does. This means your code can only include strings inside require statements.

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

https://github.com/systemjs/systemjs

like image 50
David Bradshaw Avatar answered Sep 28 '22 08:09

David Bradshaw