1

I am porting a vanilla javascript project to webpack. Previously, a whole bunch of javascript files were imported in <script> tags. Now I'm putting them all in bundle.js using webpack.

One issue I have is that previously I had a file "utils.js" with extra Date prototypes and things, e.g.:

Date.prototype.addDays = function(days) {
    var dat = new Date(this.valueOf());
    dat.setDate(dat.getDate() + days);
    return dat;
}

This file defined these things in global scope, so they were available everywhere.

When compiling my project with webpack, how can I achieve a similar thing?

user31415629
  • 925
  • 6
  • 25
  • Ideally, you aren't doing this. You should be using a module system to import your `utill.js` file. If you really must there are several solutions here https://stackoverflow.com/a/40416826/1048479 – Nick Tomlin Jul 21 '17 at 13:50
  • 1
    Modifying built-in prototypes is generally considered bad practice. – SLaks Jul 21 '17 at 13:50
  • @SLaks Thanks for the heads-up. Is there a pattern you'd recommend for this situation instead? I have a few extra things on top of `Date` that are used in a lot of places. – user31415629 Jul 21 '17 at 13:53
  • As @SLaks told you should never do this, if a function `addDays` is added to the standard, or if another library that also has follows the bad practice by modifying the Date object adds such a function, and those functions have a different signature or behaviour then yours, then it would either break your code or your code might break other third party code. You should always use utility functions or an own class like [momentjs](https://momentjs.com/) does. Only extend native types if you create polyfills for function that will or are added to the standard. – t.niese Jul 21 '17 at 13:54
  • @t.niese Thanks, I understand why I shouldn't do it. So is standard practice to create my own `MyDate` subclass and use that instead? – user31415629 Jul 24 '17 at 13:14

0 Answers0