Alias External Module in TypeScript

2019-08-08 20:41发布

I'm working on a project where I want to package my source in to multiple modules (in different files). I do this so I can include only certain pieces on certain pages to reduce the overall weight.

The problem I'm having is I can't figure out a syntax which will let me alias the external modules, and I really don't want to have to write out the full module every time (since it's usually something like A.B.C.D for organization).

When I compile, I have a script which grabs all the files, so I have the external definition file as the first parameter.

If I write out the whole module (A.B.C.D.MyClass), it recognizes that. If I try to do:

module MyModule {
    import ABCD = A.B.C.D;

    export MyClass {
        //...
        public myFunc(obj:ABCD.MyClass) {}
    }
}

It'll tell me that 'The name "ABCD" does not exist in the current scope."'

If it matters, I export all of my classes, but don't export any modules. I generate the definition file which is included (so the definition file which contains A.B.C.D is first in my list when I compile).

Any ideas?

Update

To elaborate on my file structure, I have something like this:

  • A
    • B
      • a.ts
      • b.ts
    • C
      • c.ts
      • d.ts

And then elsewhere I may also have:

  • A
    • D
      • e.ts
      • f.ts
      • E
        • g.ts
        • h.ts

In this case, I would build the first set into something like A.B.ts by compiling them with something like:

tsc A/B/a.ts A/B/b.ts A/B/C/c.ts A/B/C/d.ts --out A.B.ts --declarations

Then, when I go to package the next I would do something like:

tsc /path/to/A.B.d.ts A/D/e.ts A/D/f.ts A/D/E/g.ts A/D/E/h.ts --out A.D.ts --declarations

I build those compiler commands dynamically by recursing through a set of files I specify so it gets those compiler things.

1条回答
趁早两清
2楼-- · 2019-08-08 20:42

If you are packaging your modules in multiple files in order to load them using the AMD module loading pattern, you need to do the following...

The name of the file is the module name, you don't add module declarations

For example...

module MyModule {
    export class MyClass {
    }
}

Should actually be MyModule.ts and look like this:

export class MyClass {
}

You would then load it using:

import my = module('MyModule');

I think you are currently trying to mix a bundling style of TypeScript code with a module style of loading, which is incompatible. When you are bundling, the file-names don't matter as you take the responsibility for getting the scripts on the page. When you are using AMD or CommonJS, you need to abide by the file naming rules (i.e. file-name equals module name) and leave out the enclosing module.

As a side note, there is a bug in 0.8.1.1 that affects this, so you may want to read through this if you are on 0.8.1.1: http://typescript.codeplex.com/discussions/405800

查看更多
登录 后发表回答