Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Wrap ES module exports in an IIFE #859

Merged
merged 8 commits into from
Sep 19, 2017
Merged

Wrap ES module exports in an IIFE #859

merged 8 commits into from
Sep 19, 2017

Conversation

Rich-Harris
Copy link
Member

Chapter 94 of the unending quest to minimise bundle size. I noticed while looking at the minified output of a @TehShrike project that a lot of variable names end up being two characters rather than just one. That's because a) a typical Svelte component declares several variables/functions (the constructor itself, any fragment functions, local CSS encapsulation helper, etc), and b) Rollup and webpack combine all the top-level variables and functions into a shared scope (known as scope hoisting).

In theory, scope hoisting makes minification easier, because module A can refer to module B's exports directly, rather than as (unmangleable) properties of a module object. In practice, however, it can mean that you have so many top-level variables that Uglify runs out of single-character names, and has to use two-character names.

Wrapping the generated module in an IIFE means there's only one top-level declaration. Empirically, this results in slightly smaller minified code (which means lower parse costs). Unminified code ends up slightly more readable, because Rollup doesn't keep renaming functions to avoid conflicts (create_main_fragment, create_main_fragment$1, create_main_fragment$2 etc). Those benefits ought to increase further if we move things out of the template object and remove the IIFE that surrounds it, per #756.

Gzipped code is actually very slightly larger, however, with the code I've tried so far. Not sure how much weight to place on this, since gzip is such a mysterious beast. So it probably warrants a bit more testing before we decide if this is a desirable change.

@Rich-Harris
Copy link
Member Author

Tried this with a couple of other codebases and I'm no longer convinced. It's not always a minification win, and it seems to always be a gzip loss. The refactoring was worthwhile though — it would now be very easy to reintroduce the IIFE if further research showed that it was generally beneficial.

@Rich-Harris Rich-Harris merged commit 6b651e4 into master Sep 19, 2017
@Rich-Harris Rich-Harris deleted the iife branch September 19, 2017 15:05
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant