DEV Community

Oliver Williams
Oliver Williams

Posted on

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

Top comments (0)