React-hot-loader: webpack Tree Shaking Fails to Remove Dead Code When Using react-hot-loader

Created on 30 Nov 2018  路  2Comments  路  Source: gaearon/react-hot-loader

Description

Seeming a bug in using react-hot-loader and Webpack tree shaking; basically tree shaking works without react-hot-loader and does not with it.

Seems CRAZY, yes... Took me a better part of an afternoon to narrow it down to this; was the last thing I was looking at.

Expected behavior

Tree shaking should work with or without using react-hot-loader

Actual behavior

When add in react-hot-loader, code that I expect to be removed is still in bundle.

Environment

React Hot Loader version: 4.3.12

Run these commands in the project folder and fill in their results:

  1. node -v: v10.14.0
  2. npm -v: 6.4.1

Then, specify:

  1. Operating system:macOS 10.14.1
  2. Browser and version: N/A

Reproducible Demo

react-hot-loader-issue

One relevant datapoint is that with the .babelrc in the project I get the following output:

$ npx webpack --mode production --display-used-exports
Hash: caa91ee215568599703c
Version: webpack 4.26.1
Time: 341ms
Built at: 11/30/2018 2:32:10 PM
Asset Size Chunks Chunk Names
bundle.js 9.96 KiB 0 [emitted] main
Entrypoint main = bundle.js
[1] ./src/math.js 685 bytes {0} [built]
[only some exports used: cube]
[2] ./src/index.js 59 bytes {0} [built]
[3] (webpack)/buildin/harmony-module.js 573 bytes {0} [built]
+ 5 hidden modules

When I remove the .babelrc in the project I get the following output:

$ npx webpack --mode production --display-used-exports
Hash: 68bc11159cb57f397389
Version: webpack 4.26.1
Time: 258ms
Built at: 11/30/2018 2:33:45 PM
Asset Size Chunks Chunk Names
bundle.js 1020 bytes 0 [emitted] main
Entrypoint main = bundle.js
[0] ./src/index.js + 1 modules 213 bytes {0} [built]
| ./src/index.js 59 bytes [built]
| ./src/math.js 154 bytes [built]
| [only some exports used: cube]

Most helpful comment

babel plugin would add some "not pure" code to every file, thus make it completely unshakable.

  • Use webpack environment plugin to provide NODE_ENV to the build, to let RHL(and react) pick the right bundle
  • Setup NODE_ENV as your own env, to let babel do the right job.
NODE_ENV=production npx webpack --mode production --display-used-exports

All 2 comments

babel plugin would add some "not pure" code to every file, thus make it completely unshakable.

  • Use webpack environment plugin to provide NODE_ENV to the build, to let RHL(and react) pick the right bundle
  • Setup NODE_ENV as your own env, to let babel do the right job.
NODE_ENV=production npx webpack --mode production --display-used-exports

FYI.. The key to making this work for me was to realize that the Babel configuration can be a JavaScript file. Have a working solution at: webpack-scratch-box-js

Was this page helpful?
0 / 5 - 0 ratings