deerchao deerchao - 3 days ago 5
TypeScript Question

TypeScript: import module with only statements

I have a

page-a.ts
which would compile into
page-a.js
:

alert('this is from page-a');


And I have a
main.ts
which compiles into
main.js
:

import pageA = module('page-a')
alert('this is from main');


And this is my
tsc
command line:

tsc --module amd page-a.ts main.ts


And I'm using
requirejs
like this:

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


I can't see the alert messagebox from
page-a
when loading the page. And in the generated scripts
main.js
, there is nothing about
page-a
.

My question is, why is this happening? And how do I force typescript to import a module that is not explicitly used by the code?

Answer

Your generated js will not import a module not explicitly used in code. Typescript is clever that way and will not generate any js for a module that is only imported and not used.

You need to :

  • export a variable in the first module AND
  • import the first module in the second module AND
  • Use the exported variable in the second module

so have page-a.js something like:

export var x = 123; // just to export something that you can use
alert('this is from page-a');

and main.ts as :

import pageA = module('page-a')
var foo = pageA.x; // If you remove this line and you will not get the alert from page-a
alert('this is from main');
Comments