I have a problem with TypeScript import/export mechanics in WebStorm.
Lets say, I have a following file, named apiUtils.ts
:
export function getUsername(req) {
return req.headers.username;
}
export default module.exports;
And I have another file, that is referencing apiUtils.ts:
import apiUtils from "../bin/apiUtils";
const req = '';
const username = apiUtils.getUsername(req);
getUsername
method is not identified on the fly and I cannot navigate to it with Ctrl + click. It is marked as unused, and I can even write the following and compile the code successfully without receiving an error:
import apiUtils from "../bin/apiUtils";
const req = '';
const username = apiUtils.getUsername(req, thereIsNoSecontArgInThisMehod);
On the other hand, if I import the method as follows:
import { getUsername } from "../bin/apiUtils";
const req = '';
const username = getUsername(req);
And everything will work as expected: I get navigation, input validation and etc.
I prefer to use import apiUtils from "../bin/apiUtils";
instead of importing each method separately, since it creates a chaos of methods, that is unclear where they belong to, if they are local or not.
Is there a way to fix the import, and get it to understand what method is referenced? Since for the runtime both ways are working the same.
This happens because of export default module.exports
construction - none of the IDEs I'm aware of can handle them.
If you like to import the entire module, use import * as <name>
construction (https://www.typescriptlang.org/docs/handbook/modules.html#import-the-entire-module-into-a-single-variable-and-use-it-to-access-the-module-exports):
export function getUsername(req) {
return req.headers.username;
}
import * as apiUtils from "../bin/apiUtils";
const req = '';
const username = apiUtils.getUsername(req);