简体   繁体   中英

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 ^\.\/.*$

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

Webpack supports dynamic requires but you need to tell it how to find the files using contexts . You could try something like that before requiring your modules:

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

If something like that doesn't work, you will need to use a different approach in your code because WebPack needs to know what modules to include in your bundle on compile time.

Create angularDependencies.js :

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM