Require JS files dynamically on runtime using webpack

前端 未结 3 1890
予麋鹿
予麋鹿 2020-12-24 07:50

I am trying to port a library from grunt/requirejs to webpack and stumbled upon a problem, that might be a game-breaker for this endeavor.

The library I try to port

3条回答
  •  被撕碎了的回忆
    2020-12-24 08:32

    There is concept named context (http://webpack.github.io/docs/context.html), it allows to make dynamic requires.

    Also there is a possibility to define code split points: http://webpack.github.io/docs/code-splitting.html

    function loadInContext(filename) { 
        return new Promise(function(resolve){
            require(['./'+filename], resolve);
        })
    }
    
    function loadModules(namesInContext){
        return Promise.all(namesInContext.map(loadInContext));
    }
    

    And use it like following:

    loadModules(arrayOfFiles).then(function(){
        modules.forEach(function(module){
            module(moduleAPI);
        })
    });
    

    But likely it is not what you need - you will have a lot of chunks instead of one bundle with all required modules, and likely it would not be optimal..

    It is better to define module requires in you config file, and include it to your build:

    // modulesConfig.js
    module.exports = [
       require(...),
       ....
    ]
    
    // run.js
    require('modulesConfig').forEach(function(module){
        module(moduleAPI);
    })
    

提交回复
热议问题