You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
_Tree shaking_ is a term commonly used in the JavaScript context for dead-code elimination. It relies on the [static structure](http://exploringjs.com/es6/ch_modules.html#static-module-structure) of ES2015 module syntax, i.e. [`import`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import) and [`export`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export). The name and concept have been popularized by the ES2015 module bundler [rollup](https://github.com/rollup/rollup).
25
22
26
-
The webpack 2 release came with built-in support for ES2015 modules (alias _harmony modules_) as well as unused module export detection.
23
+
The webpack 2 release came with built-in support for ES2015 modules (alias _harmony modules_) as well as unused module export detection. The new webpack 4 release expands on this capability with a way to provide hints to the compiler via the `"sideEffects"``package.json` flag to denote which files in your project are "pure" and therefore safe to prune if unused.
27
24
28
25
T> The remainder of this guide will stem from [Getting Started](/guides/getting-started). If you haven't read through that guide already, please do so now.
29
26
@@ -107,23 +104,62 @@ function cube(x) {
107
104
Note the `unused harmony exportsquare` comment above. If you look at the code below it, you'll notice that `square` is not being imported, however, it is still included in the bundle. We'll fix that in the next section.
108
105
109
106
110
-
## Minify the Output
107
+
## Mark the file as side-effect-free
108
+
109
+
In a 100% ESM module world, identifying side effects is straightforward. However, we aren't there just yet, so in the mean time it's necessary to provide hints to webpack's compiler on the "pureness" of your code.
110
+
111
+
The way this is accomplished is the `"sideEffects"` package.json property.
112
+
113
+
```json
114
+
{
115
+
"name":"your-project",
116
+
"sideEffects":false
117
+
}
118
+
```
119
+
120
+
All the code noted above does not contain side effects, so we can simply mark the property as `false` to inform webpack that it can safely prune unused exports.
111
121
112
-
So we've cued up our "dead code" to be dropped by using the `import` and `export` syntax, but we still need to drop it from the bundle. To do that, we'll add a minifier that supports dead code removal -- the [`UglifyJSPlugin`](/plugins/uglifyjs-webpack-plugin) -- to our configuration...
122
+
T> A "side effect" is defined as code that performs a special behavior when imported, other than exposing one or more exports. An example of this are polyfills, which affect the global scope and usually do not provide an export.
113
123
114
-
Let's start by installing it:
124
+
If your code did have some side effects though, an array can be provided instead:
115
125
116
-
```bash
117
-
npm install --save-dev uglifyjs-webpack-plugin
126
+
```json
127
+
{
128
+
"name":"your-project",
129
+
"sideEffects": [
130
+
"./src/some-side-effectful-file.js"
131
+
]
132
+
}
118
133
```
119
134
120
-
And then adding it into our config:
135
+
The array accepts relative, absolute, and glob patterns to the relevant files. It uses [micromatch](https://github.com/micromatch/micromatch#matching-features) under the hood.
136
+
137
+
T> Note that any imported file is subject to tree shaking. This means if you use something like `css-loader` in your project and import a CSS file, it needs to be added to the side effect list so it will not be unintentionally dropped in production mode:
138
+
139
+
```json
140
+
{
141
+
"name":"your-project",
142
+
"sideEffects": [
143
+
"./src/some-side-effectful-file.js",
144
+
"*.css"
145
+
]
146
+
}
147
+
```
148
+
149
+
Finally, `"sideEffects"` can also be set from the [`module.rules` config option](https://github.com/webpack/webpack/issues/6065#issuecomment-351060570).
150
+
151
+
## Minify the Output
152
+
153
+
So we've cued up our "dead code" to be dropped by using the `import` and `export` syntax, but we still need to drop it from the bundle. To do that, we'll use the `-p` (production) webpack compilation flag to enable the uglifyjs minification plugin.
154
+
155
+
T> Note that the `--optimize-minimize` flag can be used to insert the `UglifyJsPlugin` as well.
156
+
157
+
As of webpack 4, this is also easily toggled via the `"mode"` config option, set to `"production"`.
T> Note that the `--optimize-minimize` flag can be used to insert the `UglifyJsPlugin` as well.
142
-
143
175
With that squared away, we can run another `npm run build` and see if anything has changed.
144
176
145
177
Notice anything different about `dist/bundle.js`? Clearly the whole bundle is now minified and mangled, but, if you look carefully, you won't see the `square` function included but will see a mangled version of the `cube` function (`functionr(e){return e*e*e}n.a=r`). With minification and tree shaking our bundle is now a few bytes smaller! While that may not seem like much in this contrived example, tree shaking can yield a significant decrease in bundle size when working on larger applications with complex dependency trees.
146
178
147
179
148
-
## Caveats
149
-
150
-
Please note that webpack doesn't perform tree-shaking by itself. It relies on third party tools like [UglifyJS](/plugins/uglifyjs-webpack-plugin/) to perform actual dead code elimination. There are situations where tree-shaking may not be effective. For example, consider the following modules:
151
-
152
-
__transforms.js__
153
-
154
-
``` js
155
-
import*asmylibfrom'mylib';
156
-
157
-
exportconstsomeVar=mylib.transform({
158
-
// ...
159
-
});
160
-
161
-
exportconstsomeOtherVar=mylib.transform({
162
-
// ...
163
-
});
164
-
```
165
-
166
-
__index.js__
167
-
168
-
``` js
169
-
import { someVar } from'./transforms.js';
170
-
171
-
// Use `someVar`...
172
-
```
173
-
174
-
In the code above webpack cannot determine whether or not the call to `mylib.transform` triggers any side-effects. As a result, it errs on the safe side and leaves `someOtherVar` in the bundled code.
175
-
176
-
In general, when a tool cannot guarantee that a particular code path doesn't lead to side-effects, this code may remain in the generated bundle even if you are sure it shouldn't. Common situations include invoking a function from a third-party module that webpack and/or the minifier cannot inspect, re-exporting functions imported from third-party modules, etc.
177
-
178
-
The code used in this guide assumes you perform tree-shaking using UglifyJS plugin. However, there are other tools such as [webpack-rollup-loader](https://github.com/erikdesjardins/webpack-rollup-loader) that may produce different results depending on your setup.
179
-
180
-
181
180
## Conclusion
182
181
183
182
So, what we've learned is that in order to take advantage of _tree shaking_, you must...
184
183
185
184
- Use ES2015 module syntax (i.e. `import` and `export`).
185
+
- Add a "sideEffects" entry to your project's `package.json` file.
186
186
- Include a minifier that supports dead code removal (e.g. the `UglifyJSPlugin`).
187
187
188
188
You can imagine your application as a tree. The source code and libraries you actually use represent the green, living leaves of the tree. Dead code represents the brown, dead leaves of the tree that are consumed by autumn. In order to get rid of the dead leaves, you have to shake the tree, causing them to fall.
0 commit comments