typescriptjs-amd

How do you prevent typescript from automatically discarding 'unused' dependencies?


Specifically imagine this scenario: I have a jquery plugin $.mega().

I can create a definition file for this plugin as follows:

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

// Extend jquery with .mega()
interface JQuery { mega(options?:any):void; }

// Declare an external module, to import mega using AMD.
// NB. You still need to setup require.js to find the bower module.
declare module mega { export function dummy():void; }
declare module "mega" { export = mega; }

Then I can invoke the plugin from a script using:

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

((...r:any[]) => {})(mega);  // <---- WTF!

$('.target').mega();

Since typescript automatically trims and discards unused dependencies as an optimization step, without actually using a module, that module is discarded, so I'm forced to 'fake' usage of the module using:

((...r:any[]) => {})(mega); 

Without this, the compiled javascript looks like:

define(["require", "exports", 'jquery'], function(require, exports, $) {
    //((...r:any[]) => {})(mega);
    $('.target').mega();
});

So, is there some way of ensuring that require includes are not 'optimized' when typescript compiles?

Either a compile flag, or a special way of building the definition file would work fine for me~

Nb. This is more for AMD, but it applies equal to commonjs modules.


Solution

  • You can use the amd-dependency to specify stuff you want hoisted in the amd define call e.g.:

    /// <amd-dependency path="mega" />