Could someone please explain exactly how exports and imports work in NodeJS using Typescript?
My setup is:
Agreed, import/export syntax is confusing for at least two reasons:
var module = require ("module");
works but that is commonjs -> no typingsimport x = require('y'
) is now deprecated in TSTL;DR;: Use the 'es6 style' syntax introduced in TS 1.5
The 'best' resource on import/export in TS I know is this
Overall I recommend reading this excellent handbook which will provide answers to most of your questions
From a default export
Something
was exported as a default (single) export ie export default Something
in ts/es6
Use
import Something from "module"
You can actually import a default export with a different name. import SomethingElse from 'module'
will also work
From named exports
Something
was exported as a named export in "module" using export {Something}
or export class|interface Something{}
in ts/es6
You want to import only that, use
import {Something} from "module"
You want to import everything that is exported from "module" under the namespace mod
import * as mod from "module
Then use const c:mod.Something = whatever
See import
s above
The form export = something
is deprecated in favor of the new ES6 style syntax. It is mostly found in definition files to express the fact that a js library exports a single function/object e.g. module.exports=something
.
Use ES6 style syntax and avoid default
exports: they have the advantage that they can be imported using a different name but
import {Something as SomethingElse} from "module"
Concretely, export whatever needs to be exported and import it specifically
In api.ts
export interface MyInterface {
}
export class MyClass {
}
In main.ts
import {MyInterface, MyClass} from './api'
There are a lot of good IDEs out there that provide excellent linting: VSCode, Atom Typescript and Webstorm to name a popular few, the first two being free and the third one even manages the imports for you.