This project is read-only.

How should I incrementally convert code to external modules?

Topics: General
Apr 3, 2014 at 1:38 PM
I have a project that uses Typescript for both the browser and the server. It has components that I can reuse in other projects.
I'm starting to convert these components to AMD/CommonJS modules.

I converted two components into external modules, in their own cloud-hosted git repositories.
This has required a fair learning curve, and I've encountered a fair bit of complexity.

I would appreciate advice for how to best manage this transition.
  • Is there a tutorial on how to do this?
    I'm sure this is a common problem, but it appears to be fairly involved.
  • How can I use an AMD module in code that is not an external module?
    This is a requirement, because I don't want to convert my entire project to external modules, just because I have one. But it seems that the language spec will convert any code that uses an import into an external module.
    For now, I'm just adding a "declare var module_name" to the components that use the AMD module, since I know that the code will not execute until after the module has been loaded.
  • I can't find a way to write a single type declaration file that works for both (1) the AMD import, and (2) the declare var method above.
    In particular, and very confusingly, it seems that the two usages require different name specification for the module in the declaration file: (1) uses "declare module 'module_name' {...}" and (2) uses "declare module module_name {...}" (without the quotes).
Apr 4, 2014 at 1:24 AM
I just discovered that the chai.d.ts declaration file for the chai test package wasn't found by tsc.

File ./test/server/csc.test.ts
/// <reference path='../../decl/import/chai.d.ts' />
import chai      = require('chai');
The command: tsc --module commonjs --outDir generated/ test/server/csc.test.ts
./test/server/csc.test.ts(17,1): error TS2071: Unable to resolve external module ''chai''.
./test/server/csc.test.ts(17,1): error TS2072: Module cannot be aliased to a non-module type.
I examined decl/import/chai.d.ts (from DefinitelyTyped) , and found that its module definition was:
declare module chai {
when I modified this to have quotes around the module name, everything worked!
declare module "chai" {
Is this difference between string and symbol(?) an accident or is it intentional?
If its intentional, what are the semantics of the difference, as I missed this from the documentation.

Apr 4, 2014 at 2:23 AM
The former is an Ambient Module Declaration, it declares an internal module (which you would not use import/require with). The latter declares an Ambient External Module Declaration. These are defined in the language specification in sections 12.1.5 and 12.1.6. You'll want to use the latter. I actually just ran into this myself recently with chai. I was intending to update it further and submit it to DefinitelyTyped but haven't gotten around to it yet.