DEV Community

Johan Melin
Johan Melin

Posted on

Do not use destructuring on import

When importing it is common to use destructuring, but it seems to have its drawbacks. By not using destructuring I got a bundled JavaScript file down from 76kb to 7kb.

I made a simple web app that prints hello world in camelcase to the console.

const lodash = require('lodash')
console.log(lodash.camelCase('hello world'))

result of webpack-bundle-analyzer

After bundling it with webpack the bundled js file was 76kb. Checking out the file with webpack-bundle-analyzer it seems to have loaded the whole of lodash. Maybe it would be smaller with destructoring.

const {camelCase} = require('lodash')
console.log(camelCase('hello world'))

Now the file is 70kb. Not a huge saving. I tried another syntax.

const camelCase = require('lodash/camelCase')
console.log(camelCase('hello world'))

result of webpack-bundle-analyzer

Now the bundled file was only 7kb, a huge saving. I got the same results whether using nodejs require or ES6 import syntax. Try it out in your own projects and see if you have similar results.

Top comments (2)

Collapse
 
rendall profile image
rendall

Webpack supports the ES6 style imports. What happens if you do
import { camelCase } from 'lodash'?

Collapse
 
theproductivecoder profile image
Johan Melin

I got the same results, I have updated the article to reflect that.