This blog post gives tips for typing import statements more quickly, including a helpful text snippet for Visual Studio Code.
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:
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.
import
statements When typing import statements manually, I’m usually doing:
import {} from '█';
import {█} from './my-module.js';
To create a snippet for Visual Studio Code that helps with import
statements, follow these steps:
File > Preferences > User Snippets
(Mac: Code > Preferences > User Snippets
)."import": {
"prefix": "imp",
"body": [
"import ${2:entities} from '${1:specifier}';$0"
],
"description": "import statement"
}
Explanation:
from
(position $1
). The placeholder you’ll see at that position is specifier
.<tab>
key, the cursor will jump to after import
(position $2
).$0
).Now editing works as follows:
imp <tab>
import entities from '█';
import entities from './my-module.js█';
<tab>
import █ from './my-module.js';
import {█} from './my-module.js';
import {foo, bar, baz█} from './my-module.js';
<tab>
import {foo, bar, baz} from './my-module.js';█