Typing import statements more quickly

(Ad, please don’t block)

This blog post gives tips for typing import statements more quickly, including a helpful text snippet for Visual Studio Code.

Does the import statement have the wrong syntax?  

People are occasionally complaining that JavaScript’s import statement has it backwards. The syntax is:

import {foo, bar, baz} from './my-module.js';

They argue that it should be:

from './my-module.js' import {foo, bar, baz};

As an aside, that’s how Python does imports.

Why? It would make auto-expansion easier: You’d first type the module specifier './my-module.js' and then the entities {foo, bar, baz}. During the latter step, the IDE already as the context for helping you out.

The reasons for the different order in JavaScript are:

  • It’s the same order as variable declarations.
  • It’s the same order as using require() in Node.js modules.

Given that you write stuff once and read it many times, the focus should be on which version is easier to read. And there, I don’t see a clear winner.

Manually typing import statements  

When typing import statements manually, I’m usually doing:

  1. Auto-expand module specifier:
    import {} from '█';
    
  2. Go back, auto-expand the entities:
    import {█} from './my-module.js';
    

A code snippet for faster entry  

To create a snippet for Visual Studio Code that helps with import statements, follow these steps:

  1. Execute the menu command File > Preferences > User Snippets (Mac: Code > Preferences > User Snippets).
  2. Pick the language “JavaScript”.
  3. Add this property to the JSON file:
    "import": {
        "prefix": "imp",
        "body": [
            "import ${2:entities} from '${1:specifier}';$0"
        ],
        "description": "import statement"
    }
    

Explanation:

  • Initially, place the cursor after from (position $1). The placeholder you’ll see at that position is specifier.
  • The next time you press the <tab> key, the cursor will jump to after import (position $2).
  • The last tab stop is after the semicolon (position $0).

Now editing works as follows:

  1. imp <tab>
  2. import entities from '█';
  3. Use auto-expansion.
  4. import entities from './my-module.js█';
  5. <tab>
  6. import █ from './my-module.js';
  7. import {█} from './my-module.js';
  8. Use auto-expansion.
  9. import {foo, bar, baz█} from './my-module.js';
  10. <tab>
  11. import {foo, bar, baz} from './my-module.js';█

Further reading