Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to require jquery via AMD in TypeScript

How do I require the jquery AMD module for my TypeScript module. For example let's say directory structure for scripts looks like this:


    jquery-1.8.2.js
    jquery.d.ts
    module.ts
    require.js

I want the generated js file from module.ts to require jquery-1.8.2.js be loaded via require.js.

Currently I have:


    import jquery = module('jquery') 

This results in The name "jquery" does not exist in the current scope.

like image 662
Mizzle-Mo Avatar asked Oct 06 '12 20:10

Mizzle-Mo


2 Answers

FOR TYPESCRIPT 1.7+

It looks like standard is changing again, where the below 0.9+ method still works, but with ES6 coming the following module loading could be used. (reference: https://github.com/TypeStrong/atom-typescript/issues/237#issuecomment-90372105)

import * as $ from "jquery";

and even partial ones

import {extend} from "jquery"; 

(this still require the jquery.d.ts, if tsd is installed - tsd install jquery)

to install tsd: npm install tsd -g

FOR TYPESCRIPT 0.9+

/// <reference path="../../typings/jquery/jquery.d.ts" />
import $ = require('jquery');

//Do your stuff

And also, if your jquery.d.ts do not define a external module, add the following to jquery.d.ts:

declare module "jquery" {
    export = $;
}
like image 124
Poul K. Sørensen Avatar answered Sep 23 '22 07:09

Poul K. Sørensen


I think a lot of the confusion around this is due to jQuery not really acting like an External Module, which inhibits the use of an import statement. The solution is quite clean, simple and elegant enough to not feel like a work-around.

I have written up a simple example of Using RequireJS and jQuery in TypeScript, which works as follows...

You grab the type definitions from Definitely Typed for RequireJS and jQuery.

You can now use raw RequireJS with static typing inside of the TypeScript file.

app.ts

///<reference path="require.d.ts" />
///<reference path="jquery.d.ts" />

require(['jquery'], function ($) {
    $(document).ready(() => {
        alert('Your code executes after jQuery has been loaded.');
    });
});

And then you only need to add the single script tag to your page:

<script data-main="app" src="require.js"></script>

Benefits over other solutions?

  1. You can update jQuery and RequireJS independently
  2. You don't have to rely on shim project being updated
  3. You don't have to manually load jQuery (or anything else that isn't "like a module" that you have a .d.ts file for)
like image 44
Fenton Avatar answered Sep 23 '22 07:09

Fenton