Proper explanation for NodeJS/Typescript Export / Import?

后端 未结 1 1334

Could someone please explain exactly how exports and imports work in NodeJS using Typescript?

My setup is:

  • NodeJS
  • Everything in Typescript
相关标签:
1条回答
  • 2021-01-30 22:22

    Agreed, import/export syntax is confusing for at least two reasons:

    • the commonjs syntax: var module = require ("module"); works but that is commonjs -> no typings
    • it changed: the syntax import x = require('y') is now deprecated in TS

    TL;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

    To import

    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

    To export

    See imports 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.

    What you should try using

    Use ES6 style syntax and avoid default exports: they have the advantage that they can be imported using a different name but

    • a default import cannot be re-exported, which may be problematic if you are writing a library
    • they will confuse a lot of IDEs (not to mention yourself) when refactoring
    • a named export can actually be locally renamed when imported i.e. 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'
    

    Linting

    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.

    0 讨论(0)
提交回复
热议问题