3

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;
}
4
  • Are you trying to create a separate file just to add methods to the prototype of Objects defined elsewhere? Commented Feb 25, 2019 at 7:49
  • @BrunoFenzl NO,... My own codes were getting bigger and that's why I decided to use webpack. And I didn't get trouble to change them to modules. But the problem was that some functions of my own use custom prototype functions of pre-defined Objects. Commented Feb 25, 2019 at 7:57
  • With pre-defined objects you mean native javascript objects or some other defined by yourself? Commented Feb 25, 2019 at 8:00
  • @BrunoFenzl I mean native object in browser, such as Element, NodeList, Date, String, etc. Commented Feb 25, 2019 at 8:07

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.