Search code examples
javascriptwebpackcode-splitting

What is an async chunk in webpack?


This is probably a dummy question but after reading split-chunks-plugin documentation and this article about code splitting, i still can't understand what an async chunk refers to.

The split-chunks-plugin documentation states about the chunks property that :

[it] indicates which chunks will be selected for optimization. If a string is provided, possible values are all, async, and initial. Providing all can be particularly powerful because it means that chunks can be shared even between async and non-async chunks.

What is the difference between an async chunk and a non-async chunk ? Is it linked to dynamic imports ?

For example :

if (myCondition) {
    import('myLib').then(myLib => {
        // Do something
    });
}

Solution

  • Reading Chunk entity from webpack source code, i found the following piece of code :

    getAllAsyncChunks() {
        const queue = new Set();
        const chunks = new Set();
    
        const initialChunks = intersect(
            Array.from(this.groupsIterable, g => new Set(g.chunks))
        );
    
        for (const chunkGroup of this.groupsIterable) {
            for (const child of chunkGroup.childrenIterable) {
                queue.add(child);
            }
        }
    
        for (const chunkGroup of queue) {
            for (const chunk of chunkGroup.chunks) {
                if (!initialChunks.has(chunk)) {
                    chunks.add(chunk);
                }
            }
            for (const child of chunkGroup.childrenIterable) {
                queue.add(child);
            }
        }
    
        return chunks;
    }
    

    What i'm seeing here is that an async Chunk is a chunk that is not present in the chunk groups initially (if (!initialChunks.has(chunk))). This let me think that an async chunk is a chunk which is loaded afterwards, for example at runtime.

    So if i get it right, the previous example will produce an async chunk :

    if (myCondition) {
        import('myLib').then(myLib => {
            // Do something
        });
    }
    

    That might also be the case for hot reloading. Hope someone can confirm that.

    EDIT :

    As @dawncold mentionned in the comment there is this nice article which explains what is a chunk in the first place.