Skip to content

Commit c1318e1

Browse files
Merge pull request #1865 from probablyup/update-se-docs
update tree shaking guide for webpack 4
2 parents 0c96dd5 + 2f19976 commit c1318e1

File tree

1 file changed

+56
-56
lines changed

1 file changed

+56
-56
lines changed

src/content/guides/tree-shaking.md

Lines changed: 56 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -8,22 +8,19 @@ contributors:
88
- avant1
99
- MijaelWatts
1010
- dmitriid
11+
- probablyup
1112
related:
12-
- title: Tree shaking with webpack 2, TypeScript and Babel
13-
url: https://alexjoverm.github.io/2017/03/06/Tree-shaking-with-Webpack-2-TypeScript-and-Babel/
14-
- title: Tree-shaking with webpack 2 and Babel 6
15-
url: http://www.2ality.com/2015/12/webpack-tree-shaking.html
16-
- title: webpack 2 Tree Shaking Configuration
17-
url: https://medium.com/modus-create-front-end-development/webpack-2-tree-shaking-configuration-9f1de90f3233#.15tuaw71x
18-
- title: Issue 2867
19-
url: https://github.com/webpack/webpack/issues/2867
20-
- title: Issue 4784
21-
url: https://github.com/webpack/webpack/issues/4784
13+
- title: "webpack 4 beta — try it today!"
14+
url: https://medium.com/webpack/webpack-4-beta-try-it-today-6b1d27d7d7e2#9a67
15+
- title: Debugging Optimization Bailouts
16+
url: https://webpack.js.org/plugins/module-concatenation-plugin/#debugging-optimization-bailouts
17+
- title: Issue 6074 - Add support for more complex selectors for sideEffects
18+
url: https://github.com/webpack/webpack/issues/6074
2219
---
2320

2421
_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).
2522

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.
2724

2825
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.
2926

@@ -107,23 +104,62 @@ function cube(x) {
107104
Note the `unused harmony export square` 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.
108105
109106
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.
111121
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.
113123
114-
Let's start by installing it:
124+
If your code did have some side effects though, an array can be provided instead:
115125
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+
}
118133
```
119134
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"`.
121158
122159
__webpack.config.js__
123160
124161
``` diff
125162
const path = require('path');
126-
+ const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
127163

128164
module.exports = {
129165
entry: './src/index.js',
@@ -132,57 +168,21 @@ module.exports = {
132168
path: path.resolve(__dirname, 'dist')
133169
- }
134170
+ },
135-
+ plugins: [
136-
+ new UglifyJSPlugin()
137-
+ ]
171+
+ mode: "production"
138172
};
139173
```
140174
141-
T> Note that the `--optimize-minimize` flag can be used to insert the `UglifyJsPlugin` as well.
142-
143175
With that squared away, we can run another `npm run build` and see if anything has changed.
144176
145177
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 (`function r(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.
146178
147179
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 * as mylib from 'mylib';
156-
157-
export const someVar = mylib.transform({
158-
// ...
159-
});
160-
161-
export const someOtherVar = 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-
181180
## Conclusion
182181
183182
So, what we've learned is that in order to take advantage of _tree shaking_, you must...
184183
185184
- Use ES2015 module syntax (i.e. `import` and `export`).
185+
- Add a "sideEffects" entry to your project's `package.json` file.
186186
- Include a minifier that supports dead code removal (e.g. the `UglifyJSPlugin`).
187187
188188
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

Comments
 (0)