webpack/examples/side-effects/template.md

59 lines
1.8 KiB
Markdown
Raw Normal View History

2017-10-12 23:32:41 +08:00
This example shows how the `sideEffects` flag for library authors works.
2017-08-08 15:40:17 +08:00
The example contains a large library, `big-module`. `big-module` contains multiple child modules: `a`, `b` and `c`. The exports from the child modules are re-exported in the entry module (`index.js`) of the library. A consumer uses **some** of the exports, importing them from the library via `import { a, b } from "big-module"`. According to the EcmaScript spec, all child modules _must_ be evaluated because they could contain side effects.
2017-08-08 15:40:17 +08:00
2017-10-12 23:32:41 +08:00
The `"sideEffects": false` flag in `big-module`'s `package.json` indicates that the package's modules have no side effects (on evaluation) and only expose exports. This allows tools like webpack to optimize re-exports. In the case `import { a, b } from "big-module-with-flag"` is rewritten to `import { a } from "big-module-with-flag/a"; import { b } from "big-module-with-flag/b"`.
2017-08-08 15:40:17 +08:00
2017-10-12 23:32:41 +08:00
The example contains two variants of `big-module`. `big-module` has no `sideEffects` flag and `big-module-with-flag` has the `sideEffects` flag. The example client imports `a` and `b` from each of the variants.
2017-08-08 15:40:17 +08:00
2017-09-14 19:35:25 +08:00
After being built by webpack, the output bundle contains `index.js` `a.js` `b.js` `c.js` from `big-module`, but only `a.js` and `b.js` from `big-module-with-flag`.
2017-08-08 15:40:17 +08:00
Advantages:
- Smaller bundles
- Faster bootup
2017-08-08 15:40:17 +08:00
# example.js
```javascript
_{{example.js}}_
2017-08-08 15:40:17 +08:00
```
# node_modules/big-module/package.json
```javascript
_{{node_modules/big-module/package.json}}_
2017-08-08 15:40:17 +08:00
```
2017-09-14 19:35:25 +08:00
# node_modules/big-module-with-flag/package.json
2017-08-08 15:40:17 +08:00
```javascript
_{{node_modules/big-module-with-flag/package.json}}_
2017-08-08 15:40:17 +08:00
```
2017-09-14 19:35:25 +08:00
# node_modules/big-module(-with-flag)/index.js
2017-08-08 15:40:17 +08:00
```javascript
_{{node_modules/big-module-with-flag/index.js}}_
2017-08-08 15:40:17 +08:00
```
# dist/output.js
2017-08-08 15:40:17 +08:00
```javascript
_{{dist/output.js}}_
2017-08-08 15:40:17 +08:00
```
# Info
## Unoptimized
2017-08-08 15:40:17 +08:00
```
_{{stdout}}_
2017-08-08 15:40:17 +08:00
```
## Production mode
2017-08-08 15:40:17 +08:00
```
_{{production:stdout}}_
2017-08-08 15:40:17 +08:00
```