Update 2022-11-30: New section on auto-importing.
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 occasionally complain that JavaScript’s import statement has it backwards. The syntax is:
import {one, two, three} from './my-module.js';
They argue that it should be:
from './my-module.js' import {one, two, three};
As an aside, that’s how Python does imports.
Why? It would make auto-expansion easier: We’d first type the module specifier './my-module.js'
and then the imported values {one, two, three}
. During the latter step, the IDE has the necessary context for helping us out.
The reasons for the different order in JavaScript are:
require()
in Node.js modules.Given that we only write code once but read it many times, the focus should be on which version is easier to read. And there, I slightly prefer JavaScript’s current syntax.
These days, I mostly write TypeScript and I mostly use Visual Studio Code (VSC).
There, auto-importing has gotten really good: If there is a value I want to import, I type its name, auto-expand it (Control-Space on macOS) and VSC imports it for me. I neither have to know the name of the module nor get its relative path right.
Additionally, I use the “Organize Imports” command (which has a keyboard shortcut that you can look up via the Command Palette) to:
import
statements When typing import statements manually:
{}
and auto-expand the module specifier: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:values} from '${1:specifier}';$0"
],
"description": "import statement"
}
Explanation:
from
(position $1
). The placeholder we’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 values from '█';
import values from './my-module.js█';
<tab>
import █ from './my-module.js';
import {█} from './my-module.js';
import {one, two, three█} from './my-module.js';
<tab>
import {one, two, three} from './my-module.js';█
Update 2017-09-20: A similar snippet is now built into Visual Studio Code for .js(x)
files (previously, only TypeScript was supported (more information).