Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 230
Doug Avatar asked Jun 10 '14 07:06

Doug


2 Answers

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

/// <amd-dependency path="mega" />
like image 65
basarat Avatar answered Nov 19 '22 19:11

basarat


A nicer solution (tested with TS 1.8):

import 'mega';

The amd-dependency triple-slash-directive seems to only work if there are other require imports; only having amd-dependency directives results in the TypeScript compiler generating JavaScript completely without a module definition.

like image 21
bcody Avatar answered Nov 19 '22 18:11

bcody