Push Module Differences To Compiler

Topics: General, Language Specification
Oct 31, 2012 at 10:49 AM

Having tried out examples using bundling, CommonJS and AMD I think the following would be a highly useful feature for the TypeScript compiler.

Where the --module flag is set to either CommonJS or AMD, the TypeScript compiler should remove module declarations that match the following rules:

  1. The module is identical to the file name
  2. The module encloses the entire contents of the file

This would allow developers to write a single .ts file that would work as a bundled JavaScript file, CommonJS module or AMD module.

Example

Sayings.ts

module Sayings {
    export class Greeter {
        greeting: string;
        constructor (message: string) {
            this.greeting = message;
        }
        greet() {
            return "Hello, " + this.greeting;
        }
    }
}
If this file was compiled with either 
--module commonjs

or

--module amd

The compiler would first remove the module declaration, before transpiling the remaining TypeScript to JavaScript.

    export class Greeter {
        greeting: string;
        constructor (message: string) {
            this.greeting = message;
        }
        greet() {
            return "Hello, " + this.greeting;
        }
    }

This allows open source projects, for example, to supply a module that includes module declarations that can be included in a CommonJS or AMD program without the consumer needed to first remove all the module declarations manually.

This would mean the language specification wouldn't need to suggest different styles for different module patterns.

Coordinator
Nov 1, 2012 at 3:36 PM
This discussion has been copied to a work item. Click here to go to the work item and continue the discussion.