VS Code: Easily convert require statements into modern ES module imports
Last updated: 10th March 2023VS Code can convert your code that uses require()
's, like this:
const path = require("path");
const crypto = require("crypto");
const fetch = require("node-fetch");
const { name } = require("./animal.js");
Into this code that uses import
's, like this:
import path from "path";
import crypto from "crypto";
import fetch from "node-fetch";
import { name } from "./animal.js";
This also works with exports
!
To use this feature:
- With the cursor next to the first
r
in the firstrequire
statement, observe three dots appear underneath ther
. - Enter
Cmd + Shift + P
. - And select
Quick fix
- The option to convert to ESM appears, select that with
Enter
.
Alternatively, click the lighbulb 💡️ icon that appears.