Skip to content

Latest commit

 

History

History
3161 lines (2389 loc) · 31.5 KB

README.md

File metadata and controls

3161 lines (2389 loc) · 31.5 KB

Modern JavaScript Snippets ⚡

Short and effective JavaScript & TypeScript snippets for the modern-day developer.


JavaScript TypeScript

Features

  • Over 200 carefully crafted snippets
  • Modern JavaScript syntax
  • Modern JavaScript APIs (Intl, URL, Navigator...)
  • Strategically placed tabstops
  • Prefixes created with exact-match in mind
  • Auto-generated documentation

Support

Only JavaScript and TypeScript will be supported. Specific frameworks get their own extensions. No bloat.

Setup

The following is not mandatory, but could provide a nicer experience. Test them out and decide what works best for you.

Look for it in user settings, or edit the settings.json directly:

"editor.formatOnSave": true,

// Tab complete snippets when their prefix match. Works best when 'quickSuggestions' aren't enabled.
"editor.tabCompletion": "onlySnippets"

Style

Most of the code snippets are without semicolons (;), except for where it allows for better tabstop management. Strings use single quotes (').

It's highly recommended to use these snippets along with Prettier/ESLint to have your code automatically formatted to your preference.

Snippet syntax

Tabstops

  • $1, $2, $3 specify cursor locations, in order in which tabstops will be visited
  • $0 denotes the final cursor position
  • Multiple occurrences of the same tabstop are linked and updated in sync

Placeholders

  • Tabstops with default values → ${1:name}

Choices

  • Tabstops with multiple values → ${1|one,two,three|}.
  • Truncated in documentation, for easier viewing → ${1|one,...|}.

Snippets

Assignments

Prefix Name Body
ca const assignment
const ${1:name} = $2
la let assignment
let ${1:name} = $2
cas const string assignment
const ${1:name} = '$2'
las let string assignment
let ${1:name} = '$2'
caa const array assignment
const ${1:arr} = [$0]
cao const object assignment
const ${1:obj} = { $0 }
dob object destructuring
const { $2 } = ${1:obj}$0
dar array destructuring
const [$2] = ${1:arr}$0

Functions

Prefix Name Body
fn function
function ${1:fn}($2) {
  $0
}
fna async function
async function ${1:fn}($2) {
  $0
}
nfn named arrow function
const ${1:fn} = ($2) => {$0}
nfna async named arrow function
const ${1:fn} = async ($2) => {$0}
af arrow function
($1) => $0
arr arrow function arrow
=> $0
afa async arrow function
async ($1) => $0
afb arrow function with body
($1) => {
  $0
}
afba async arrow function with body
async ($1) => {
  $0
}
iife immediately-invoked function expression
(($1) => {
  $0
})($2)

Flow control

Prefix Name Body
iff if statement
if (${1:true}) {$2}
ifel if/else statement
if (${1:true}) {$2} else {$3}
ifei if/else-if statement
if (${1:true}) {$2} else if ($3) {$4}
el else statement
else {
  $0
}
ei else if statement
else if ($1) {$2}
ter ternary operator
$1 ? $2 : $3
tera ternary expression assignment
const ${1:name} = $2 ? $3 : $4
sw switch
switch ($1) {
  case $2 : $3
  default: $0
}
scase switch case
case $1 : $2
tc try/catch
try {
  $1
} catch (err) {
  $0
}
tcf try/catch/finally
try {
  $1
} catch (err) {
  $2
} finally {
  $3
}
tf try/finally
try {
  $1
} finally {
  $2
}

Loops

Prefix Name Body
flr for loop (range)
for (let ${1:i} = 0; ${1:i} < ${2:5}; ${1:i}++) {
  $0
}
rfl reverse for loop
for (let ${1:i} = ${2:iter}.length - 1; ${1:i} >= 0; ${1:i}--) {
  $0
}
fin for...in loop
for (let ${1:key} in ${2:array}) {
  $0
}
fof for...of loop
for (let ${1:item} of ${2:items}) {
  $0
}
fofa for await...of loop
for await (let ${1:item} of ${2:items}) {
  $0
}
wl while loop
while (${1:true}) {
  $0
}
dwl do while loop
do {
  $0
} while ($1)

Classes

Prefix Name Body
cs class
class $1 {
  $0
}
cse class extends
class $1 extends ${2:Base} {
  $0
}
csp class proprety
${1:name} = ${2:value}
csc class with constructor
class $1 {
  constructor($2) {
    $0
  }
}
csec class extends with constructor
class $1 extends ${2:Base} {
  constructor($3) {
    $0
  }
}
cst class constructor
constructor($1) {
  $0
}
get getter
get ${1:property}() {
  $0
}
set setter
set ${1:property}(${2:value}) {
  $0
}
gs getter and setter
get ${1:property}() {
  $0
}
set ${1:property}(${2:value}) {
  $0
}
met method
${1:name}($2) {
  $0
}
meta async method
async ${1:name}($2) {
  $0
}

Array methods

Prefix Name Body
aat array.at
$1.at(${2:0})
fe Array.forEach()
$1.forEach((${2:item}) => {
  $0
})
map Array.map()
$1.map((${2:item}) => ${3})
fmap Array.flatMap()
$1.flatMap((${2:item}) => ${3})
reduce Array.reduce()
$1.reduce((${2:acc}, ${3:curr}) => {
  $0
}, ${4:initial})
reduceRight Array.reduceRight()
$1.reduceRight((${2:acc}, ${3:curr}) => {
  $0
}, ${4:initial})
filter Array.filter()
$1.filter((${2:item}) => ${3})
find Array.find()
$1.find((${2:item}) => ${3})
findl Array.findLast()
$1.findLast((${2:item}) => ${3})
findi Array.findIndex()
$1.findIndex((${2:item}) => ${3})
findli Array.findLastIndex()
$1.findLastIndex((${2:item}) => ${3})
every Array.every()
$1.every((${2:item}) => ${3})
some Array.some()
$1.some((${2:item}) => ${3})
reverse Array.reverse()
$1.reverse()
sort Array.sort(
$1.sort((${2:a}, ${3:b}) => $4)
group Array.group()
$1.group((${2:item}) => $3)
groupMap Array.groupToMap()
$1.groupToMap((${2:item}) => $3)
mapStr Array.map() to string
$1.map(String)
mapNum Array.map() to number
$1.map(Number)
mapBool Array.map() to boolean
$1.map(Boolean)
filterTruthy Array.filter() truthy
$1.filter(Boolean)
arfr Array.from
Array.from($1)

Modules

Prefix Name Body
im import from module
import { $2 } from '${1:module}'
imd import default
import ${2:thing} from '${1:module}'
ima import as
import ${2:*} as ${3:name} from '${1:module}'
imf import file
import '$1'
imp import dynamic
import('$0')
impa await import dynamic
await import('$0')
imm import meta
import.meta.$0
ex export
export $0
exd export default
export default $0
exf export from
export { $0 } from '${1:module}'
exa export all from
export * from '${1:module}'
exo export object
export const ${1:name} = { $0 }
efn export function
export function ${1:name}($2) {
  $0
}
edfn export default function
export default function ${1:name}($2) {
  $0
}
enfn export named arrow function
export const ${1:name} = ($2) => {$0}

Promises

Prefix Name Body
fet fetch
await fetch($1).then(res => res.json())
feta fetch assignment
const ${1|data,...|} = await fetch($2).then(res => res.json())
npr promise
new Promise((resolve, reject) => {
  $0
})
prr Promise.resolve
Promise.resolve($1)
prj Promise.reject
Promise.reject($1)
then promise then()
$1.then((${2:value}) => $0)
catc promise catch()
$1.catch((${2:err}) => $0)
thenc promise then().catch()
$1.then((${2:value}) => $3)
  .catch((${4:err}) => $5)
pra Promise.all
Promise.all($1)
pras Promise.allSettled
Promise.allSettled($1)
pran Promise.any
Promise.any($1)

Literals, operators, expressions

Grouping them all together for now

Prefix Name Body
arr array literal
[$0]
ob object literal
{ }
tl template literal
`$0`
tle template literal operation
${${1:name}}$0
ns new Set
new Set($1)
nm new Map
new Map($1)
am array merge
[...$1]
om object merge
{ ...$1 }
or OR (||)
|| $0
and AND (&&)
&& $0
lt less than (<)
< $0
lte less than or equal to (<=)
<= $0
gt greater than (>)
> $0
gte greater than or equal to (>=)
>= $0
nc nullish coalescing (??)
?? $0
neq strict non-equality (===)
!== $0
eq strict equality (===)
=== $0
ora logical OR assignment (||=)
||= $0
nca nullish coalescing assignment (??=)
??= $0
plus addition
+ $0
minus subtraction
- $0
mul multiplication
* $0
div division
/ $0
mod modulo
% $0
inc addition assignment
+= ${0:1}
sub subtraction assignment
-= ${0:1}
mula multiplication assignment
*= ${0:1}
diva division assignment
/= ${0:1}
col colon
: 

Objects

Prefix Name Body
oe Object.entries
Object.entries($0)
ofe Object.fromEntries
Object.fromEntries($0)
ok Object.keys
Object.keys($0)
ov Object.values
Object.values($0)

Utilities

Prefix Name Body
pi parse int
parseInt($1, ${2|10,...|})
pf parse float
parseFloat($1)
uniq array of unique values
[...new Set($0)]
seq sequence of 0..n
[...Array(${1:length}).keys()]
cp copy to clipboard
navigator.clipboard.writeText($1)
nurl new URL
new URL($1)
sp url search params
new URLSearchParams($1)
spa url search params assignment
const ${1:params} = new URLSearchParams($2)
spg get search param
${1:params}.get($2)
sps set search param
${1:params}.set($2, $3)

Returns and exceptions

Prefix Name Body
ret return
return $0
reo return object
return {
  $0
}
rei return object inline
return ({$0})
terr throw error
throw new ${1|Error,...|}($0)

Timers

Prefix Name Body
si set interval
setInterval(() => {
  $0
}, ${1:1000})
st set timeout
setTimeout(() => {
  $0
}, ${1:1000})
sim set immediate
setImmediate(() => {
  $0
})
prnt process next tick
process.nextTick(() => {
  $0
})

JSON

Prefix Name Body
jsp JSON parse
JSON.parse(${1:json})
jss JSON stringify
JSON.stringify(${1:value})
jssf JSON stringify (formatted)
JSON.stringify(${1:value}, null, 2)

Console

Prefix Name Body
cl console.log
console.log($0)
ci console.info
console.info($1)
cdi console.dir
console.dir($1)
ce console.error
console.error($1)
cw console.warn
console.warn($1)
ct console.time
console.time('$1')
$0
console.timeEnd('$1')
ctb console.table
console.table($1)
clr console.clear
console.clear()
clm console.log message
console.log('$0')
clo console.log object
console.log({ $0 })
clc console.log clipboard
console.log({ $CLIPBOARD })
cll console.log (labeled)
console.log('$1 :', $1$2)
cil console.info (labeled)
console.info('$1 :', $1$2)
cel console.error (labeled)
console.error('$1 :', $1$2)
cwl console.warn (labeled)
console.warn('$1 :', ${2:$1})

Dates

Prefix Name Body
nd new Date()
new Date($1)
nds new Date() with date string
new Date('${1:2023}-${2:|01,...|}-${3:31}')
now Date.now()
Date.now()
tls Date.toLocaleString()
$1.toLocaleString('${2|en-US,...|}'$3)

DOM

Prefix Name Body
qs query selector
${1:document}.querySelector('$2')
qsa query selector all
${1:document}.querySelectorAll('$2')
qsaa query selector all as array
[...${1:document}.querySelectorAll('$2')]
ael event listener
${1:document}.addEventListener('${2:click}', (e$3) => $0)
qsae query selector with event listener
${1:document}.querySelector('$2')?.addEventListener('${3:click}', (e$4) => $0)
gid get element by id
${1:document}.getElementById('$2')

Node

Prefix Name Body
req require
require('${1:module}')
rqr require assignment
const $1 = require('${1:module}')
mex module.exports
module.exports = {$1}

Intl

Internationalization API

Prefix Name Body
inf Intl.NumberFormat
new Intl.NumberFormat('${1|en-US,...|}'$3).format($2)
infs Intl.NumberFormat style
new Intl.NumberFormat('${1|en-US,...|}', {
  style: '${3|decimal,...|}',$4
}).format($2)
infc Intl.NumberFormat as currency
new Intl.NumberFormat('${1|en-US,...|}', {
  style: 'currency',
  currency: '${3|USD,...|}',$4
}).format($2)
infp Intl.NumberFormat as percentage
new Intl.NumberFormat('${1|en-US,...|}', {
  style: 'percent',$3
}).format($2)
infu Intl.NumberFormat as unit
new Intl.NumberFormat('${1|en-US,...|}', {
  style: 'unit',
  unit: '${3|acceleration-g-force,...|}',
  unitDisplay: '${4|long,...|}',$0
}).format($2)
idtf Intl.DateTimeFormat
new Intl.DateTimeFormat('${1|en-US,...|}'$3).format($2)
idtfs Intl.DateTimeFormat with style
new Intl.DateTimeFormat ('${1|en-US,...|}', {
  dateStyle: '$3',$0
}).format($2)

Types

Prefix Name Body
aia is array
Array.isArray($0)
tof typeof
typeof $1
tofc typeof check
typeof $1 === '${2|undefined,...|}'
iof instanceof
$1 instanceof ${0:Class}
isnil is nil
$1 == null
nnil is not nil
$1 != null
isnan is NaN
isNaN($0)
nnan is not NaN
!isNaN($0)

Testing

Prefix Name Body
desc describe
describe('$1', () => {
  $0
})
cont context
context('$1', () => {
  $0
})
it test (synchronous)
it('$1', () => {
  $0
})
ita test (asynchronous)
it('$1', async () => {
  $0
})
itc test (callback)
it('$1', (done) => {
  $0
  done()
})
bf before test suite
before(() => {
  $0
})
bfe before each test
beforeEach(() => {
  $0
})
aft after test suite
after(() => {
  $0
})
afe after each test
afterEach(() => {
  $0
})

Globals

Prefix Name Body
wlo window.location
window.location
wlh window.location.href
window.location.href

Misc

Prefix Name Body
us 'use strict' statement
'use strict'
prs process.server
process.server
prc process.client
process.client
env env variable
process.env.$0
envv env variable (meta)
import.meta.env.$0

TypeScript

Available only where TypeScript is supported

Declarations

Prefix Name Body
cat const assignment (typed)
const ${1:name}: ${2:string} = $3
lat let assignment (typed)
let ${1:name}: ${2:string} = $3
caat array assignment (typed)
const ${1:arr}: ${2:string}[] = [$0]
caot object assignment (typed)
const ${1:obj}: ${2:object} = { $0 }

Types

Prefix Name Body
int interface
interface ${1:Model} {
  $0
}
inte interface extends
interface ${1:Model} extends ${2:Base} {
  $0
}
tp type
type ${1:Model} = $2
tpu type union
type ${1:Model} = ${2:string} | ${3:number}
tpi type intersection
type ${1:Model} = $2 & $3

DOM

Prefix Name Body
qst query selector (typed)
${1:document}.querySelector<${2|HTMLElement,...|}>('$3')
qsat query selector all (typed)
${1:document}.querySelectorAll<${2|HTMLElement,...|}>('$3')
qsaat query selector all as array (typed)
[...${1:document}.querySelectorAll<${2|HTMLElement,...|}>('$3')]
gidt get element by id (typed)
${1:document}.getElementById<${2|HTMLElement,...|}>('$3')

Running locally

# ensure Deno is installed
# https://deno.land/manual@v1.29.1/getting_started/installation

# generate .code-snippets and documentation
npm run generate