7

I created this example

module.js

import moment from "moment";

export function square(x) {
    return x * x;
}

export function cube(x) {
    return moment.format(x * x * x);
}

main.js

import {square} from "./module";

console.log(square(1));

I noticed that it also includes moment library in my bundle although I don't use it in square function.. If I remove the moment import from module.js tree shaking works fine and i only see square in my bundle.

Is this how tree shaking suppose to work? is there a workaround except than splitting my code in different files if I want to use an external library in my module.js file?

2 Answers2

3

Ok I figured it out! I had to specifically set sideEffects for that module in webpack.config rules..

 module: {
    rules: [
        {
            include: path.resolve(__dirname, "node_modules/moment"),
            sideEffects: false
        }
    ]
},
0

Moment.js is a fantastic time & date library with lots of great features and utilities. However, if you are working on a performance sensitive web application, it might cause a huge performance overhead because of its complex APIs and large bundle size. Also, it is highly based on OOP APIs, which makes it fail to work with tree-shaking, thus leading to a huge bundle size and performance issues.

If you are not using timezone but only a few simple functions, you can have a look at other alternatives like dayjs, date-fns which have smaller core and provide very similar APIs.

enter image description here

Detailed explanation and alternate plan can be found on https://github.com/you-dont-need/You-Dont-Need-Momentjs

Dharman
  • 30,962
  • 25
  • 85
  • 135
abhishek khandait
  • 1,990
  • 2
  • 15
  • 18