Skip to content

Instantly share code, notes, and snippets.

@farsightsoftware
Created September 5, 2023 12:07
Show Gist options
  • Save farsightsoftware/7a553ada9fd632fca5ed4c68bf2c4a7b to your computer and use it in GitHub Desktop.
Save farsightsoftware/7a553ada9fd632fca5ed4c68bf2c4a7b to your computer and use it in GitHub Desktop.
Tree shaking example using default export

Quick and dirty project to test the claim default exports defeat tree-shaking. Indicates that no, default exports themselves don't defeat tree-shaking. (An anti-pattern using them would, but not defaults themselves.)

Note: I dislike default exports and strongly recommend not using them when you can avoid them (which is always, other than when interface with some libraries/packages that require them).

To replicate:

  1. Grab these files into a local directory.

  2. Do npm i

  3. Do npm run build

  4. Look at the generated JavaScript file in the dist directory. The text unused doesn't appear, because the unused function was removed by tree-shaking.

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<title>Tree Shaking</title>
<style>
body,
html {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
box-sizing: border-box;
}
*,
*:before,
*:after {
box-sizing: inherit;
}
</style>
<script src="./main.js" type="module"></script>
</head>
<body>
</body>
</html>
import x from "./mod.js";
x();
export default function x() {
console.log("This is the default export");
}
export function unused() {
console.log("This is the unused export");
}
{
"name": "treetest",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "vite build"
},
"keywords": [],
"author": "T.J. Crowder <tj.crowder@farsightsoftware.com>",
"license": "MIT",
"devDependencies": {
"vite": "^4.4.9"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment