2

When I use webpack and UglifyjsWebpackPlugin, I try to minify code:

// this is test.js
export const ceil = Math.ceil

export const random = Math.random

// webpack entry
import { ceil } from './test'

export default ceil(3.3)

I got :

 // formated
 "use strict";
 n.d(t,"a",function(){return r});
 var r=Math.ceil;
 Math.random// still exist?

and if I minify

// this is test.js
export const ceil = Math.ceil

export const random = 1 // or string 

I will get normal.

So, why Math.random still exist? tree shaking not work?

webpack: 3.10.0
UglifyjsWebpackPlugin: 1.1.6

Thanks!

JJJ
  • 49
  • 5

1 Answers1

0

It's a little unclear from your question, but Math.random is part of the javascript standard library, and is always included in every browser. As such, you can't tree shake it but you also don't need to worry about its size: you "get" Math.random for free.

Put another way, Tree shaking is a tool to reduce the size of your bundle. The definition for Math.random isn't part of your bundle to begin with, and it doesn't contribute to your bundle size.

(note: the same is true of Math.ceil)

John
  • 9,249
  • 5
  • 44
  • 76
  • Thanks for your answer. I have a question about your answer: why I 'get' `Math.random`, if I write many `Math.random`, it won't add the size? I am so sorry I am't an english speaker, thanks for your time. – JJJ Jul 30 '18 at 23:24
  • @JJJ `Math.random` returns a value. So with `const random = Math.random`, `random` is equal to a random value, it is not equal to the `Math.random` function. Tree shaking an app might remove `const random = Math.random`, if `const random` is never used, but it will not remove `Math.random` (because again, `Math.random` is provided by the browser). Notice how in your first minified example, `const random` was removed. Make sense? – John Jul 30 '18 at 23:51
  • Also, its a little unclear what part of your first minified example you added as a comment, but if a lone `Math.random` call was indeed still present after minification in your first example (i.e. the file ends simply with `Math.random` and you're questioning why the call to `Math.random` is still there), that I couldn't tell you. That might be an error in the tree shaking algorithm. I originally assumed that your first minified file looked like `"use strict"; n.d(t,"a",function({return r}); var r=Math.ceil;` and everything else was added by you as comments. – John Jul 30 '18 at 23:57