Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is re-exporting modules harmful for tree-shaking?

I've come into an argument with my co-workers for which we can't seem to find an answer from any official source (MDN, webpack documentation, ...). My research hasn't yielded much either. There seems to be doubt even when it comes to importing as well.

Our setup is Webpack, Babel, and a typical React / Redux app. Take this example:

export * from './actions';
export * from './selectors';
export * from './reducer';

export { default } from './reducer';

This allows me to separate a Redux module into logical sections, making the code easier to read and maintain.

However, it is believed by some of my co-workers that export * from may, in fact, harm webpack's tree-shaking capabilities, by tricking it into believing an export is used when it is in fact just being re-exported.

So my question is, are there any facts proving or disproving this?

like image 262
pbondoer Avatar asked Feb 20 '19 18:02

pbondoer


People also ask

Does tree shaking remove unused imports?

Tree shaking dynamic importsDynamic imports resolve the entire module — with its default and named exports — without tree shaking unused imports.

What is tree shaking and why is it important?

Tree shaking is a term commonly used within a JavaScript context to describe the removal of dead code. It relies on the import and export statements to detect if code modules are exported and imported for use between JavaScript files.

How webpack detect the dead code that can help in tree shaking?

Tools like webpack will detect dead code and mark it as “unused module” but it won't remove the code. Webpack relies on minifiers to cleanup dead code, one of them is UglifyJS plugin, which will eliminate the dead code from the bundle. It only works with import and export . It won't work with CommonJS require syntax.


1 Answers

It is believed that export * from may harm webpack's tree-shaking capabilities, by tricking it into believing an export is used when it is in fact just being re-exported.

No, import/export declarations don't do anything but set up an alias to the exported variable, they do not count as a "use". Given their semantics, they are tracked specially by any bundler and will not adversely affect tree-shaking.

Not even a properly done renamed alias will break that:

export { X as Y } from '…';

import { X as Y } from '…';
export { Y }

import { X } from '…';
export { X as Y }

but usage in a statement would count as usage and break (non-sophisticated) optimisations:

import { X } from '…';
export const Y = X; // avoid!

So my question is, are there any facts proving or disproving this?

You can just try it out and see it work.

like image 198
Bergi Avatar answered Oct 23 '22 02:10

Bergi