Nick Zuber
Nick Zuber

Reputation: 5637

TypeScript: Imported Module Not Compiling

So I have a simple TypeScript file that imports a local TypeScript module. Everything links fine when I compile it, but the compiled JavaScript file is trying to require my TypeScript module which I'm importing, instead of compiling it.

Here's an example of my file layout:

module.ts

declare module "MyModule" {
  export var name: string;
}

test.ts

/// <reference path="../../src/module.ts"/>

import MyModule = require('MyModule');

var myName = MyModule.name;
myName = 'Nick';

console.log(myName);

I attempt to compile it like so:

ntsc mockup.ts and also tried (with the same results) ntsc mockup.ts --module commonjs

It compiles to this:

test.js

/// <reference path="../../src/modern/needle.ts"/>
"use strict";
var MyModule = require('MyModule');
var myName = MyModule.name;
myName = 'Nick';
console.log(myName);

It also attempts to compile module.ts but the file that comes from it is completely empty. Can anyone help me figure out what's going wrong? The line var MyModule = require('MyModule'); clearly isn't correct (the file wrong run because of it). I suspect something might be wrong with my module file, especially since it's not compiling correctly. Any help would be greatly appreciated.

Upvotes: 0

Views: 2337

Answers (2)

basarat
basarat

Reputation: 276255

It also attempts to compile module.ts but the file that comes from it is completely empty

Because module.ts only has declarations. Declarations are just hints to the compiler and will not do any actual JavaScript emit.

Upvotes: 1

Ryan Cavanaugh
Ryan Cavanaugh

Reputation: 221342

Your file layout should look something like this:

test.ts

import mod = require('./MyModule');

console.log(mod.name);

MyModule.ts

export var name = 'Hello, world!';

Run tsc --module commonjs test.ts to compile, then node test.js to execute.

Upvotes: 1

Related Questions