Skip to content

Instantly share code, notes, and snippets.

@willwillems
Last active March 23, 2022 14:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save willwillems/abb1b39c207737b107b72db7f8a051df to your computer and use it in GitHub Desktop.
Save willwillems/abb1b39c207737b107b72db7f8a051df to your computer and use it in GitHub Desktop.
VS Code Regex find and replace require syntax with import syntax

Simple require imports, for example const bar = require("foo"):

  • Regex: (const|var|let)\b\s+(\w+)\s+=\s+require\s*\(["']([\/\w\-]+)["']\)\n
  • Replace: import $2 from "$3"\n

One-liner require & config/compute, for example const router = require("express").Router({ mergeParams: true }):

  • Regex: (const|var|let)\b\s+(\w+)\s+=\s+require\s*\(["'](\w+)["']\)(?=\S+)
  • Replace: import $3 from "$3" \n$1 $2 = $3

WARNING: Using this regex one can end up with duplicate variable names (when $2 === $3).

Relative module imports, for example const bar = require("./bar/foo"):

  • Regex: (const|var|let)\b\s+(\w+)\s+=\s+require\s*\(["']([\.\/\w\-]+)["']\)\n
  • Replace: import $2 from "$3"\n

One-line import, no variable, for example: require("module"):

  • Regex: require\s*\(["']([\/\w\-]+)["']\)\n
  • Replace: import "$1"\n

Append .mjs or .js to import statements:

  • Regex: import ([\w\-_]+)\s+from\s+["'](?=\.)([\w\-\.\/]+)["']
  • Replace: import $1 from "$2.js"

Other replacements

  • module.exports = with export default
  • exports.([\w\-_]+) with export const $1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment