Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting large typescript file into module across multiple files

I currently have a large typescript file that I want to split up. There are a few functions and variables only used within the file, and a number of classes. It currently looks something along these lines:

var numbers = [1, 2, 3];
function formatDate() {...}

class Widget { ... }
class Section { ... }

I've tried putting this in a module and splitting it across a few files:

//Widget.ts
module ReportTemplate {
    export class Widget { ... }
}

//Section.ts
module ReportTemplate {
    export class Section { ... }
}

//ReportTemplate.ts
/// <reference path="Widget.ts"/>
/// <reference path="Section.ts"/>
module ReportTemplate {
    var numbers = [1, 2, 3];
    function formatDate() { ... }
}

I was hoping that this would be equivalent to my original file, but wrapped in a module, but what I've found is that Widget and Section are unable to access numbers and formatDate.

I wasn't sure if I'd just misunderstood the references, so I've tried adding references to ReportTemplate.ts in Section.ts and Widget.ts but it hasn't helped. The only way I've found to allow Section.ts and Widget.ts to access numbers and formatDate is to export them, but I don't want them to be accessible outside the module.

I've read quite a bit about typescript modules, but I haven't found any examples that are the same as what I'm trying to do, so I'm still confused. Am I trying to do something which can't be done, or am I simply going about it the wrong way?

like image 865
Tim Avatar asked Sep 29 '15 14:09

Tim


1 Answers

I would suggest you move to the ES6 style of modules & imports. Instead of what is now called "namespaces" using the keyword module.

To adapt your example above do this...

//Widget.ts
export class Widget { ... }

//Section.ts
export class Section { ... }

//ReportTemplate.ts
import {Widget} from './Widget.ts';
import {Section} from './Section.ts';
var numbers = [1, 2, 3];
function formatDate() { ... }
function doStuff() {
  // use the classes you imported
  var widget = new Widget();
  var section = new Section();
}

You will have to tell tsc what module syntax to use, and target at least ES5:

//tsconfig.json
{
  "module": "common",
  "target": "ES5"
}

There was conversation regarding this change when it when into TypeScript here

like image 70
Brocco Avatar answered Sep 28 '22 10:09

Brocco