Where to put 'monkeypatches' in Nuxt.js?

Viewed 233

where can I put 'monkeypatches' and 'my extensions' to prototypes of basic javascript objects in Nuxt framework to have it's functionality accesible accros all files ?

for example:

String.prototype.capitalize = function () {

    return this.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}
2 Answers

This is prototype pollution and a bad practice. There are better ways to share common function:

  1. Put them in a utility file (e.g. under utils/helpers.js and import them from there
  export const capitalize = s => s.replace(/\w\S*/g, 
    txt => txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase()
  )
  1. Use a Nuxt plugin to inject the helper function, so it's available in all components (though this might be a bit overkill here). See here

I highly suggest to avoid prototype pollution.

Hello you can create a ~/plugins/my-extensions.js file with your code sample. This code will be run once (server-side and client-side as well) and will make available your extensions methods everywhere.

Do not forget to register your plugin in nuxt.config.js:

export default {
  plugins: ['~/plugins/my-extensions.js']
}
Related