DEV Community

Oliver Williams
Oliver Williams

Posted on

9 1 1

Using ES Modules with Fastify

Documentation for Fastify, as well as for all official Fastify plugins, uses the older Node CommonJS module syntax. You can however, make use of ES modules.

To use ES modules in Node, you can set "type": "module" in your package.json. Then, instead of const fastify = require('fastify')({ logger: true }) you can do:

import Fastify from 'fastify';
const fastify = Fastify({ logger: true });
Enter fullscreen mode Exit fullscreen mode

The same is true for the official plugins:

import fastifyFormbody from 'fastify-formbody';
fastify.register(fastifyFormbody);
Enter fullscreen mode Exit fullscreen mode

__dirname and __filename

One difference between CommonJS modules and ES modules is that __filename and __dirname are not available in ES modules. As the official Node docs suggest, they can be replicated with via import.meta.url

import path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

import fastifyStatic from 'fastify-static';

fastify.register(fastifyStatic, {
    root: path.join(__dirname, 'public'),
    prefix: '/public/',
});
Enter fullscreen mode Exit fullscreen mode

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay