Ionic 2 Angular 2 Global Import Extension Methods

I've made some extensions to the Date prototype, for example:

interface Date {
    YearsFromToday(): number;
}

Date.prototype.YearsFromToday = function (): number {
    // implementation 
}

      

I am using the ionic2 tutorial --v2 template which is a pretty standard layout - app.html, app.ts, app.module, etc.

I was wondering if there is an easy way to declare this globally. I'm not sure where exactly to do this in the project?

+3


source to share


1 answer


Place the monkey patch code in the file. You can call it monkey-patch-date.ts , for example:

monkey patch-date.ts

interface Date {
    YearsFromToday(): number;
}

Date.prototype.yearsFromToday = function (): number {
    // implementation 
}

      

and then import it into main.ts or whatever your input module:

main.ts



import './monkey-patch-date';

      

As an alternative. You can make it a module that exports its monkey patcher if you want to be more explicit to cause you to do something dangerous.

monkey patch-date.ts

declare global {
    interface Date {
        yearsFromToday(): number;
    }
}

export default function () {
    Date.prototype.yearsFromToday = function (): number {
        // implementation 
    };
}

      

And import it like

main.ts



import monkeyPatchDate from './monkey-patch-date';
monkeyPatchDate();

      

Another alternative, especially useful for library authors, is to allow but not require decapitation of patches while still demonstrating functionality.

Here's an example:

date-augmentation / index.ts

export function yearsFromToday(date: Date): number {
    // implementation 
}

      

<strong> date-augmentation / monkey-patch.ts

import {yearsFromToday} from './index';

declare global {
    interface Date {
        yearsFromToday(): number;
    }
}

Date.prototype.yearsFromToday = function() {
    return yearsFromToday(this);
}

      

Now the consumer can either pay the Date prototype like a monkey by doing

import 'date-augmentations/monkey-patch';

      

Can access export functions without decapitating anything

import {yearsFromToday} from 'date-augmentations';

const date = new Date('12-12-2023');
const yft = yearsFromToday(date);
console.log(yft); // prints 6

      

+2


source







All Articles