Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import TypeScript Module from a Uri

Tags:

typescript

Is it possible within TypeScript to import a module or reference a definition file from a uri?

We are using RequireJS for our application and would like to serve some of our definition files and TypeScript (or generated JavaScript) files from a CDN rather than including them all directly in our projects.

Referencing Definition Files
In TypeScript we can reference a definition file like this:

/// <reference path="jquery-1.8.3.d.ts" />

However, what we would like to do is this:

/// <reference path="https://github.com/borisyankov/DefinitelyTyped/raw/master/jquery/jquery-1.8.d.ts" />

export class UsesSomethingFromJQuery {

    TestMethod(element: JQuery) {
        // Do something with the supplied element
    }

}

NOTE: I'm not planning to use Boris' github link as the CDN. I used the link to demonstrate the concept.

Importing TypeScript Files
We would also like to import modules from a common website, like this:

import OtherModule = module('http://some-internal-site/ts/other');

export class UsesSomethingFromOther {

    TestMethod(c: OtherModule.TestClass) {

    }

}

However, I get the error 'Invalid import path' when providing a uri for the module.

What We're Trying to Solve
We have a library of TypeScript files that generate JavaScript for our controls, some REST service wrappers, and other utilities. We'd like to use these common controls in other web applications.

When we have a TypeScript file that is specific to one of our web sites (hence not part of the common core) that relies upon classes defined within the common core, we would like to reference the dependency using a uri. Hence the question above.

If these were simply JavaScript source files we would host them on an internal CDN and reference from there but with the TypeScript compilation step we run into a problem. Are we approaching this in the wrong way? Is there a better way?

like image 663
Stuart Thompson Avatar asked Dec 13 '12 17:12

Stuart Thompson


1 Answers

I think it is a fine idea to server your JavaScript output from a CDN, which would impact either your module-loader or your script tags, but the .d.ts files aren't required at runtime.

You could adjust this example of RequireJS and jQuery in TypeScript to load files remotely like this...

  1. Local definitions files (.d.ts)
  2. Remote runtime files, using require.config.

app.ts

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

require.config({
  paths: {
    'jquery' : 'https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min'
  }
});

require(['jquery'], function (jquery) {
    jquery(document).ready(() => {
        alert('Your code executes after jQuery has been loaded.');
    });
});
like image 167
Fenton Avatar answered Sep 18 '22 11:09

Fenton