Sneakster
Sneakster

Reputation: 155

Extending jQuery with typescript and webpack

I'm converting a project using typescript using all global definitions and direct javascript compilation to using modules and assembling them into a bundle with webpack. In some cases I'll attach a method to jQuery to create the class.

So I might have some classes/interfaces like this:

interface IMyClassOptions {
    //....
}

class MyClass {
    constructor(target: JQuery, options?: IMyClassOptions){
        //....
    }
}

interface JQuery {
    myClass(options?: IMyClassOptions): JQuery;
}

$.fn.myClass = function(options?: IMyClassOptions) {
    const instance = new MyClass(this, options);
    this.data("myClass", instance);
    return this;
}

Which works fine when compiled directly to javascript with the script dropped in the page. But now if I export interface IMyClassOptions and export class MyClass and assemble with webpack, then just those items get exported and the code to attach to jQuery doesn't get included in the bundle.

I can think of a few workarounds:

But I'd really like something automated that doesn't require extra code to set things up

Upvotes: 2

Views: 356

Answers (1)

Sneakster
Sneakster

Reputation: 155

Welp I ended up figuring it out.

Solution is to perform the operation in a function call to assign a static property in the class definition like:

declare global {
    interface JQuery {
        myClass(): JQuery;
    }
}

export class MyClass {
    static readonly bootstrapped = (() => {
        if(!("myClass" in $.fn)){
            $.fn.myClass = function(options?: IMyClassOptions){
                this.data("myClass", new MyClass(options));
                return this;
            }
        }

        return true;
    })();

And then if only the extended jQuery method is used need to import "./myclass"

Upvotes: 4

Related Questions