Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add prototype function of variable constructor with webpack

I have been making my own JS library and I'm trying to remake it with webpack.

In my original file, I used prototype function for variable constructor like this:

Date.prototype.fooFunc = function(e){
// return something
};
String.prototype.barFunc = function(e) {
// return something
};


var Library = function(e){
var date = new Date();

this result = date.fooFunc().barfunc();
};

and the codeline for variable constructor prototype function gets plenty long. So that I'm trying to make a seperated file for prototype funcs.

But I have no idea how to export a property of pre-defined variables in JS module system. How can I walk through it?

Solved

prototypes.js

if ( typeof Date.prototype.myFunc == undefined ) {
  var foo = new Date();
  return foo.something();
};

// no export

webpack.config.js

module.exports = (env, options) => {
  const config = {
    target: 'web',
    entry: {
      'my-library': [
        './src/prototypes.js',
        './src/index.js'
      ],
    },
    output: {
      filename: '[name].min.js',
      library: 'myLibrary',
      libraryTarget: 'var',
      libraryExport: 'default',
      path: path.resolve(__dirname, 'dist')
    },
    optimization: {
      splitChunks: {
        cacheGroups: {
          commons: {
            test: /[\\/]node_modules[\\/]/,
            name: 'vendors',
            chunks: 'all'
          }
        }
      }
    },
  }
  return config;
}
like image 386
Bad Dobby Avatar asked Dec 07 '25 10:12

Bad Dobby


1 Answers

You Don't need to export prototype methods. As soon as you add them to an Object, they are integral part of it and will be always accessible.

You have to include the file with your prototype extensions after the Object you are extending and before they are used somewhere else in your build process.

If you are extending solely javascript native objects like Date and Math, include your extensions file as the very first in your build.

like image 172
BrunoFenzl Avatar answered Dec 10 '25 01:12

BrunoFenzl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!