简体   繁体   中英

Typescript, Requirejs, import statement and aliases

With Java, import is really easy and clear.

You import with the following statement :

import fr.domain.MyUtils;

Then you can use it like this:

MyUtils.myStaticMethod();

You need to namespace MyUtils only if there are two in the same file.

With Typescript AMD and requirejs it seems to be more complicated.

Here the import statement:

import u = require('fr/domain/MyUtils');

And the way to use it:

u.fr.domain.MyUtils.myStaticMethod();

Quite verbose...

The only way I found so fare to use an alias was to double the import statement:

import u = require('fr/domain/MyUtils');
import MyUtils = u.fr.domain.MyUtils;

After doing that you can write this in a module:

MyUtils.myStaticMethod();

It's cleaner but Eclipse TS plugin get completely lost with this and auto completion become erratic. In Visual Studio auto completion is OK but "F12 Go to definition" has to be done twice which is annoying.

Is there a better way to do this ? Or should we just keep namespaces as short as we can ?

You're doing it wrong.

Your 'fr/domain/MyUtils' module should be exporting only whatever is supposed to be MyUtils. ie it should look like this:

export function myStaticMethod() { /* ...code... */ }

It should not be exporting some global namespace object, and it should not be adding anything to some global namespace object that you get from somewhere else. The natural placement of module files in directories is the way you create “namespaces” when you work with external modules.

If you do it correctly then your consumer looks like this:

import MyUtils = require('fr/domain/MyUtils');
MyUtils.myStaticMethod();

or, even more properly using ES module syntax:

import { myStaticMethod } from 'fr/domain/MyUtils';
myStaticMethod();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM