B
B
Bowen2016-11-30 13:06:25
Angular
Bowen, 2016-11-30 13:06:25

Is it possible to move Promise & require.ensure into a separate function and include files through it?

Hello others.
Lazy loading modules in angular2 in conjunction with webpack looks something like this:

loadChildren: () => new Promise(resolve => {
        (require as any).ensure([], (require: any) => {
            resolve(require("./module_path")["ModuleName"]);
        }, "chunkName")
})

This construction is cumbersome and therefore I want to put all this stuff into a separate function and load modules through it.
Example:
function loadModule(path: string){
    // обработка строки path
    let p = new Promise(resolve => {
        (require as any).ensure([], (require: any) => {
            resolve(require(path)[ModuleName]);
        }, chunkName)
    });
    return p;
}
loadChildren: () => loadModule('./module_path#ModuleName')

The problem is that when compiling, I get one notice and one error:
Notice:
Critical dependency: require function is used in a way in which dependencies cannot be statically extracted

Mistake:
var p = new Promise(function (resolve) {
        !(function webpackMissingModule() { var e = new Error("Cannot find module \".\""); e.code = 'MODULE_NOT_FOUND'; throw e; }()).ensure([], function (require) {
            resolve(require(path)[moduleName]);
        }, chunkName);
    });

Of course, I googled, found and tried a lot, but nothing helped.
I would like to understand what is the problem, what am I doing wrong, how to solve it all?
I would appreciate any help/advice!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
vybornova, 2018-10-12
@vybornova

If still relevant, then the second example does not work due to the fact that path is passed through a parameter, and not passed as an explicit line to require. I'll show you with an example, this is how it works:

export const loadFoo = () => new Promise<any>((resolve, reject) => {
    require.ensure(["Foo/path"], require => {
        resolve(require("Foo/path"));
    }, error => reject(error));
});

But it's not like this:
export const load = (path: string) => new Promise<any>((resolve, reject) => {
    require.ensure([path], require => {
        resolve(require(path));
    }, error => reject(error));
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question