Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Static files and Vite

Besides HTML, a page needs styles, scripts and images. AdonisJS has two paths for them: ready files that are served as is live in public/, while CSS and JavaScript that need bundling go through Vite — the frontend bundler built into the Web kit.

The public folder

Everything in public/ is available at an address from the site root. Put an image public/logo.png there and show it in the layout:

{{-- resources/views/components/layout.edge --}}
<header>
  <a href="/"><img src="/logo.png" alt="My blog" width="120"></a>
</header>

The image also opens directly at http://localhost:3333/logo.png. The @adonisjs/static package serves the files, and its settings are in config/static.ts.

Styles and scripts through Vite

The style and script sources live in resources/css/app.css and resources/js/app.js. Which files to bundle is set in vite.config.ts in the project root:

// vite.config.ts
import { defineConfig } from 'vite'
import adonisjs from '@adonisjs/vite/client'
 
export default defineConfig({
  plugins: [
    adonisjs({
      entrypoints: ['resources/css/app.css', 'resources/js/app.js'],
      reload: ['resources/views/**/*.edge'],
    }),
  ],
})

entrypoints are the build's entry files. reload tells Vite to reload the page in the browser whenever any Edge template changes.

Including them in a template

Add the @vite tag to the layout's <head>:

{{-- resources/views/components/layout.edge --}}
<head>
  <meta charset="utf-8">
  <title>{{ title ?? 'My blog' }}</title>
  @vite(['resources/css/app.css', 'resources/js/app.js'])
</head>

In development the tag loads files from the Vite server, which starts together with node ace serve --hmr. Change a color in app.css — the page updates by itself.

Write a couple of rules in resources/css/app.css:

/* resources/css/app.css */
body {
  font-family: system-ui, sans-serif;
  max-width: 720px;
  margin: 0 auto;
}
 
.post-card {
  border-bottom: 1px solid #ddd;
  padding: 16px 0;
}

The post list becomes a narrow centered column, and the cards are separated by lines.

Building for the server

Before deploying, the files are bundled:

node ace build

Vite puts the result into public/assets/ inside the build folder, and on the server the @vite tag inserts file names with hashes like app-3f2a1c.css by itself. You change nothing in the templates.

Common mistake

Do not link the sources directly with <link href="/resources/css/app.css">. The resources folder is not served as static files, so the browser gets a 404, and after the build the sources are not on the server at all. Include styles and scripts from resources only through @vite, and link directly only to files from public/.

Thanks for reading!

Donate to the site — we work hard for you.