Search code examples
javascriptnode.jstypescriptrequire

Which of the listed import statements are identical?


I have identified the following import statements in node. Do all the statements below import mathgraph with a different namespace scope, or which import styles are identical?

const/var/let mathgraph = require('mathgraph');

import * as mathgraph from 'mathgraph';
import mathgraph from 'mathgraph';
import { mathgraph } from 'mathgraph';
import mathgraph = require('mathgraph');

Solution

  • // mathgrab lib
    export default { foo: 'foo' }
    
    // your code
    import mathgraph from 'mathgraph';
    mathgrab.foo
    

    This imports the default export.


    // mathgrab lib
    export const someObject = { foo: 'foo' }
    
    // your code
    import { someObject } from 'mathgraph';
    someObject.foo
    

    This imports a named export.


    // mathgrab lib
    export const someObject = { foo: 'foo' }
    export default { bar: 'bar' }
    
    // your code
    import mathgraph, { someObject } from 'mathgraph';
    mathgrab.someObject.foo
    mathgrab.default.bar
    

    You can even combine these two to import both kinds of exports in one line.


    // mathgrab lib
    export const someObject = { foo: 'foo' }
    export default { bar: 'bar' }
    
    // your code
    import * as mathgraph from 'mathgraph';
    mathgrab.someObject.foo
    mathgrab.default.bar
    

    This imports all exports as a single object. The default export will be on the default property of this object.


    const mathgraph = require('mathgraph');
    

    This only works in node, and is functionally the same as import *, but it's a dynamic runtime require, rather than than a compile time import. That means that typescript can't use the types of the imported file. require is just a function, so it returns a value of type any, thereby missing out on all typing info.

    Don't use require with typescript, you pretty always want to use import instead.


    import mathgraph = require('mathgraph');
    

    And lastly, this is invalid syntax. So don't do that.