Add file extensions to your dynamic imports to reduce size

lgraziani2712

Luciano Graziani

Posted on April 12, 2019

Add file extensions to your dynamic imports to reduce size

UPDATE: Here's a codesandbox with this situation: https://codesandbox.io/s/webpack-dynamic-import-duplication-array-gv0gq

TL;DR

Instead of writing dynamic imports like this

import(`./my-path/${fileName}`)

Write them like this

import(`./my-path/${fileName}.ext`);

It will reduce the bundle size!

Long explanation

Yesterday I was reading the generated code by webpack and found something interesting:

var map = {
  "./en/_extras": [
    3,
    0
  ],
  "./en/_extras.js": [
    3,
    0
  ],
  "./en/color": [
    8,
    5
  ],
  "./en/color.js": [
    8,
    5
  ],
  // The rest of the files
};

That map object represent every possible chunk for an specific dynamic import, and it was twice the size I expected.

Then it hit me: I didn't wrote the file extension in my dynamic imports. When I did it, each of those objects reduced its sizes to match the numbers of files!

It's not like it will massively reduce your bundle size, but it's something you could get for free!

💖 💪 🙅 🚩
lgraziani2712
Luciano Graziani

Posted on April 12, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related