Code Monkey home page Code Monkey logo

Comments (4)

emil-1996 avatar emil-1996 commented on June 12, 2024

I have the same problem when i have "type": "module" not working

from fastify-autoroutes.

GiovanniCardamone avatar GiovanniCardamone commented on June 12, 2024

i have to build aslo for es modules (mjs),

right now i am using typescript to build the package and i don't know if i can output mjs with it, without using another transpiler (like babel).

right now the workaround is to use "commonjs" type.

from fastify-autoroutes.

emil-1996 avatar emil-1996 commented on June 12, 2024

I convert your code to es

import fastifyPlugin from 'fastify-plugin';
import glob from 'glob-promise';
import process from 'process';
import path from 'path';
import fs from 'fs';

export const ERROR_LABEL = 'fastify-autoroutes';

async function loadModule(name, path) {
	const module = await import(path);

	if (typeof module === 'function') {
		return module;
	}
	if (typeof module === 'object' && 'default' in module && typeof module.default === 'function') {
		return module.default;
	}
	throw new Error(`${exports.ERROR_LABEL}: invalid route module definition (${name}) ${path}. Must export a function`);
}

export default fastifyPlugin(async (fastify, options, next) => {
	const {dir, prefix: routePrefix} = {
		...options, dir: options.dir || './routes', prefix: options.prefix || '',
	}

	let dirPath;

	if (path.isAbsolute(dir)) {
		dirPath = dir
	} else if (path.isAbsolute(process.argv[1])) {
		dirPath = path.join(process.argv[1], dir)
	} else {
		dirPath = path.join(process.cwd(), process.argv[1], dir)
	}

	if (!fs.existsSync(dirPath)) {
		return next(new Error(`${ERROR_LABEL} dir ${dirPath} does not exists`))
	}

	if (!fs.statSync(dirPath).isDirectory()) {
		return next(new Error(`${ERROR_LABEL} dir ${dirPath} must be a directory`))
	}

	let routes = await glob(`${dirPath}/**/[!.]*.{ts,js}`)
	const routesModules = {}

	// glob returns ../../, but windows returns ..\..\
	routes = routes.map((route) => path.normalize(route).replace(/\\/g, '/'))
	dirPath = path.normalize(dirPath).replace(/\\/g, '/')

	// console.log({ routes })

	for (const route of routes) {
		let routeName = route
			.replace(dirPath, '')
			.replace('.js', '')
			.replace('.ts', '')
			.replace('index', '')
			.split('/')
			.map((part) => part.replace(/{(.+)}/g, ':$1'))
			.join('/')

		routeName = !routeName ? '/' : `${routePrefix}${routeName}`

		// console.log({ routeName })

		routesModules[routeName] = (await loadModule(routeName, route))(fastify)
	}

	for (let [url, module] of Object.entries(routesModules)) {
		for (const [method, options] of Object.entries(module)) {
			if (url.endsWith('/') && url !== '/') {
				url = url.slice(0, -1)
			}
			fastify.route({
				method: method.toUpperCase(), url: url, ...options,
			})
		}
	}
}, {
	fastify: '>=3.0.0', name: 'fastify-autoroutes',
})

It's working for me, but if you add support es (native) I would like prefer use your solution

from fastify-autoroutes.

GiovanniCardamone avatar GiovanniCardamone commented on June 12, 2024

i have to add a build step to produce both (commonjs, es module) output. In this way, node can pick module by itself.

I can't replace this or i will break any other commonjs application

from fastify-autoroutes.

Related Issues (12)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.