Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add jquery to window object when using angular, typescript, webpack

I have backported the ng2 webpack guide to ng1 - https://angular.io/docs/ts/latest/guide/webpack.html

I have 3 entry files - polyfill.ts, vendor.ts and main.ts. This is the way webpack loads them into the browser. I have added the following to vendor.ts

import 'jquery';
import 'angular';
import 'angular-ui-router';
import 'angular-ui-bootstrap';
import 'angular-loading-bar';
import 'checklist-model';
import 'restangular';
import 'lodash';
import 'moment';
import 'bootstrap-datepicker';

and the following to main.ts

import "./styles/main.scss";

import app from './app';
import * as $ from 'jquery';

var datepicker = $.fn.datepicker.noConflict();
$.fn.bootstrapDP = datepicker;

angular.bootstrap(document, [app], {
    strictDi: true
});

The development workflow is working really well but the only thing is because jquery/$ is not on the window object when angular loads, jqLite is used instead which makes it hard for me to use jquery plugins. Below is my date picker directive that I have ported from another project that is using ES5:

export function DatePickerDirective($timeout: ng.ITimeoutService): ng.IDirective {
    'ngInject';

    return {
        restrict: 'A',
        require: '?ngModel',
        link: link
    };

    function link(scope: any, element: any, attrs: any, ngModel: any) {
        'ngInject';

        $timeout(function () {
            element.bootstrapDP({
                format: 'dd/mm/yyyy',
                forceParse: true,
                autoclose: true,
                todayBtn: 'linked',
                todayHighlight: true,
                daysOfWeekHighlighted: [0, 6]
            });

        });

        scope.$on('$destroy', function () {
            element.bootstrapDP('remove');
        });

    }

}

The 'element' is referring to jqLite and hence it can't find the .bootstrapDP property. Is there a way to setup typescript or webpack to make angular uses jquery?

like image 658
the-a-train Avatar asked May 16 '26 08:05

the-a-train


1 Answers

I ended up adding the following to my main.ts and getting rid of the no conflict on the datepicker.

import app from './app';
import * as $ from 'jquery';

declare var window : any; <--- THIS LINE
window.$ = window.jQuery = $; <--- AND THIS LINE

angular.bootstrap(document, [app], {
    strictDi: true
});

It stills feels a bit gross but I didn't want to rely on any CDN's

like image 198
the-a-train Avatar answered May 18 '26 23:05

the-a-train



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!