VanillaCreamJS: Superpoteri al tuo JavaScript

Immagine di copertina

Cos’è VanillaCreamJS?

VanillaCreamJS è una libreria moderna che dona reattività e potenza al JavaScript nativo, senza bisogno di build tool o configurazioni complesse. Pensata per migliorare la produttività, è leggera, modulare, e perfettamente integrabile con qualsiasi backend.

“Raffina il Vanilla JavaScript, senza tradirlo.”

Creata e mantenuta da me, questa libreria si pone l’obiettivo di semplificare lo sviluppo moderno mantenendo la sintassi familiare del JavaScript puro.

Perché usarla?

VanillaCreamJS è unica per diversi motivi:

  • Aggiunge reattività nativa al DOM.
  • Funziona senza algoritmi di diffing o virtual DOM.
  • Ha un’API snella ma potente.
  • Ti aiuta a migliorare la padronanza del JavaScript puro.
  • Si integra con qualsiasi stack backend.
  • Perfetta per progetti piccoli e medi, ma flessibile anche in architetture più complesse.
  • Unisce il meglio di HTMX, Vue e Alpine in un’unica sintesi leggera.

La funzione $

Il cuore di VanillaCreamJS è la funzione $, che restituisce uno o più elementi DOM potenziati, accompagnati da uno stato reattivo opzionale.

<div id="app">
  <div id="el"></div>
</div>
<script>
  const [el, s] = $('#el', { counter: 10 })
  el.text = () => s.counter
  el.onClick(() => s.counter++)
</script>

In questo esempio:

  • el rappresenta il nodo DOM selezionato.
  • s è un oggetto reattivo.
  • Ogni modifica a s.counter aggiorna automaticamente il contenuto di el.

Proprietà disponibili

Gli elementi gestiti con $ possono usare shortcut reattive:

  • .text, .html – per aggiornare contenuto testuale o HTML.
  • .class, .attr, .data, .css – per gestire classi, attributi, data-* e stili.
  • .on.event, .onClick, ecc. – per gestire eventi nativamente.

Esempio di toggle di classe:

<div id="app">
  <div id="el">box</div>
</div>
<script>
  const [el, state] = $('#el', { hl: true })
  el.class.highlighted = () => state.hl
  el.on.click(() => s.hl = !state.hl)
</script>

Reattività avanzata e massiva

VanillaCreamJS consente di impostare più proprietà reattive contemporaneamente:

el.css.set({
  color: 'blue',
  backgroundColor: () => state.bg,
  width: () => state.x + 'px'
})

el.class.set({
  active: () => state.active,
  box: () => state.counter >= 10
})

Supporta anche oggetti complessi e array mutabili, rendendo la reattività profonda:

<div id="app">
  <div ref="box"></div>
  Insert fruit: <input ref="fruit">
  <button ref="btn">Add Fruit</button>
</div>
<script>
  const { box, fruit, btn, state } = $.refs('#app', { fruits: ['apple', 'kiwi'] })

  box.text = () => 'Fruits: ' + state.fruits.join(', ')

  btn.onClick(() => {
    state.fruits.push(fruit.attr.value)
    fruit.attr.value = ''
  })
</script>

Riferimenti semantici con $.refs

Con $.refs potete accedere in un colpo solo a tutti gli elementi referenziati via ref nel template:

<div id="app">
  <div ref="el"></div>
  <button ref="btn">Update</button>
</div>
<script>
  const { el, btn, state } = $.refs('#app', { counter: 0 })

  el.text = () => `Counter: ${state.counter}`
  btn.onClick(() => state.counter++)
</script>

È anche possibile raggruppare i riferimenti per namespace:

<button ref="btn.AZ">A-Z</button>
<button ref="btn.ZA">Z-A</button>
<button ref="btn.Random">Shuffle</button>

Attributi x-: HTML dichiarativo

VanillaCreamJS consente di scrivere logica reattiva direttamente nel markup HTML:

<div id="app">
  <div x-text="`Counter: ${state.counter}`"></div>
  <button x-event.click="() => state.counter++">Increase</button>
  <div x-if="state.counter === 10">Counter is 10!</div>
</div>
<script>
  const { state } = $.refs('#app', { counter: 0 })
</script>

AJAX semplificato

Con JavaScript

const result = await $.post('https://api.site.com/data', {
  data: { name: 'VanillaCream', type: 'framework' }
})
el.html = result

Direttamente nel DOM

<div ref="el"></div>
<script>
  const { el } = $.refs('#app')
  el.post('https://api.site.com/data', {
    start: () => el.text = 'Loading...',
    data: { name: 'VCream' }
  })
</script>

HTML only

<div x-get="{
  url: 'https://httpbin.org/html',
  headers: { 'X-Test': '123' },
  on: 'click'
}">Load content</div>

Integrazione con il backend

VanillaCreamJS si adatta perfettamente a back-end dinamici. Ecco un esempio con Laravel:

<div id="app">
  <div ref="box"></div>
  Insert fruit: <input ref="fruit">
  <button ref="btn">Add Fruit</button>
</div>
<script>
  const { box, fruit, btn, state } = $.refs('#app', {
    fruits: @json($fruits)
  })

  box.text = () => 'Fruits: ' + state.fruits.join(', ')

  btn.onClick(async () => {
    const v = fruit.attr.value
    await $.get('/add-fruit', { data: { fruit: v } })
    state.fruits.push(v)
    fruit.attr.value = ''
  })
</script>

Cos’altro offre?

VanillaCreamJS include anche:

  • computed properties
  • side effects
  • componenti frontend leggeri
  • subset dinamici
  • stati globali condivisi

Il tutto con una sintassi chiara e moderna.

Conclusione

VanillaCreamJS è molto più di una libreria: è un approccio elegante, moderno ed estremamente pratico per lavorare in modo reattivo con il DOM senza rinunciare alla purezza del JavaScript nativo.

Conosci meglio chi ha scritto questo articolo

Riccardo Degni

𝗦𝗲𝗻𝗶𝗼𝗿 𝗳𝘂𝗹𝗹-𝘀𝘁𝗮𝗰𝗸 𝗱𝗲𝘃𝗲𝗹𝗼𝗽𝗲𝗿 I am a senior web developer, active both on front-end and back-end. I am both a developer with a strong foundation in the new technologies such as full Javascript-based envirnonments and object-oriented programming on the server-side (PHP, Node and Java), and a designer who makes powerful and WordPress-free templates. Alongisde my Dev Team, I make next-gen, full-featured web-applications. I am also a programmer/software developer working with C/C++.

I am a Zend Certified Engineer (PHP) and a Oracle Certified Engineer (Java).

𝗧𝗲𝗮𝗰𝗵𝗲𝗿 I work as a professional teacher (with more than 5000 hours of experience in real classes), teaching full-stack web development to my students. I have been teaching at international Academies such as Accenture, Everis, GiGroup, Microsoft Academy, HRM Group, TackTMI, Avanade and national Academies such as MADE4CODE Academy, Digitazon, Global Learning, Epicode, Virvelle, DSTech, FormYou, Sinervis. I’ve been teaching at some notable names in Milano area: Linea ATC, Citel spa, Ricasoli Group, Office Depot, Fulcri srl, CRSLaghi Group.

I’m currently teaching: HTML, CSS, Tailwind, Javascript, TypeScript, Vue, React, Next, Node, Express, Svelte, SvelteKit, PHP, SQL, Laravel, C, C++, Python, Java and Spring.

𝗢𝗽𝗲𝗻 𝘀𝗼𝘂𝗿𝗰𝗲 𝘀𝗼𝗳𝘁𝘄𝗮𝗿𝗲 When I was 19 I created the GX framework and the moo.rd library which have been used all around the world, both reviewed world-wide, such as at Ajaxian. I then created the DOMmy.js Javascript Library which has been published and reviewed on Web Resource Depot.

𝗪𝗿𝗶𝘁𝗲𝗿 I am an author on Amazon Direct Publishing (DP), dedicated to delivering high-quality content on web programming and other topics.

I also write full programming tutorials for Codemotion, HTML.it and Mr.Webmaster.

I wrote the full guide to Object-Oriented Programming in PHP (2009), the full guide to MooTools framework (2008), the full guide to w3.css framework and the full guide to CodeIgniter PHP framework for HTML.it magazine. I wrote the DOMmy.js guide on Web Designer Depot. In the past, I interviewed the Leader of jQuery, John Resig, and the Leader of MooTools, Valerio Proietti.

𝗩𝗶𝗱𝗲𝗼-𝗰𝗼𝘂𝗿𝘀𝗲 𝗺𝗮𝗸𝗲𝗿 I developed full video-courses for MADE4CODE Academy, Epicode (Java OOP Fundamentals course), Centro Ricerche Studi dei Laghi (Agile Software Development and Design Patterns course) and Sinervis (HTML, CSS, Javascript/jQuery, PHP, and Java course).

𝗥𝗲𝘀𝗲𝗮𝗿𝗰𝗵𝗲𝗿 I am a Research Consultant for IT at Centro Ricerche Studi dei Laghi.

Foto di Riccardo Degni

Partners

Community, aziende e persone che supportano attivamente il blog

Vuoi diventare tech content creator? 🖊️

Se ti va di raccontare la tua esperienza nel mondo tech, questo è il posto giusto.

Cerchiamo voci autentiche, esempi pratici e punti di vista utili per chi legge.

Scrivici a collaborazioni[at]theredcode.it con una proposta: idea, taglio del contenuto e una breve presentazione. Non vediamo l'ora di leggere la tua esperienza!

Invia la tua idea