Dynamic System.import with webpack?

后端 未结 4 1045
[愿得一人]
[愿得一人] 2020-12-10 08:12

I am trying to port some ES6 code I have written that uses systemjs + Babel.

I didn\'t have any problem porting most of the code.

However, I have some code t

4条回答
  •  盖世英雄少女心
    2020-12-10 08:29

    You don't have such thing as "dynamic loading" in webpack (since the bundler needs to go down to all your module dependencies). The closest thing to what you want to achieve (and the right way to do it in webpack) would be to use require.ensure - see documentation.

    One way of turning your SystemJS code into webpack would be:

    function load(moduleName) {
        switch (moduleName) {
            case 'foo':
                require.ensure([], require) => {
                    const foo = require('./foo.js');
                    // do something with it
                }
                break;
            case 'bar':
                require.ensure([], require) => {
                    const bar = require('./bar.js');
                    // do something with it
                }
                break;
        }
    }
    

    I'd advise you to make a load function encapsulating each require.ensure (you may want to manage callbacks differently).

    You can check out an example here

提交回复
热议问题