npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

recma-module-to-function

v1.0.0

Published

A recma plugin to convert an ESTree module into a function body.

Readme

recma-module-to-function

github actions codecov npm version npm downloads

A recma plugin to convert an ESTree module into a function body. It’s compatible with MDX.

Table of Contents

Installation

npm install recma-module-to-function

Usage

You can use this with recma to convert a module to a function body.

import { recma } from 'recma'
import recmaModuleToFunction from 'recma-module-to-function'

const source = `
import assert from 'node:assert/strict'

export { assert }
`

const file = recma()
  .use({ settings: { module: true } })
  .use(recmaModuleToFunction)
  .processSync(source)

console.log(String(file))

API

This module exports a single function named recmaModuleToFunction.

recma().use(recmaModuleToFunction, options?)

Convert an estree module into a function body. This modifies the input AST.

Options

  • importName: A custom name for the import. By default, import() expressions are used. If this option is given, import expressions and import meta properties are transformed into identifiers using this name. (type: string)

Examples

Evaluate JavaScript

You can use recma to transform a JavaScript module, then use the AsyncFunction constructor to evaluate the result. Note that imports will be resolved relative to the module that invokes the AsyncFunction constructor.

import { recma } from 'recma'
import recmaModuleToFunction from 'recma-module-to-function'

const source = `
import os from 'node:os'
import recmaModuleToFunction from 'recma-module-to-function'

export const home = os.homedir()
export { recmaModuleToFunction }
`

const file = recma()
  .use({ settings: { module: true } })
  .use(recmaModuleToFunction)
  .processSync(source)

const AsyncFunction = (async () => {
  // We only define this function to get its constructor.
}).constructor

const fn = new AsyncFunction(String(file))
const result = await fn()

console.log(result)

Module map

It’s often desirable to explicitly define which modules may be imported. One strategy to do this is to define map of imports that can be imported. Then define a custom import function.

import { recma } from 'recma'
import recmaModuleToFunction from 'recma-module-to-function'

import * as b from './b.js'

const a = { A: 1 }

const modules = new Map([
  ['a', a],
  ['b', b]
])

async function customImport(name) {
  const module = modules.get(name)
  if (module) {
    return module
  }

  throw new Error(`Cannot find module '${name}'`)
}

const importName = '_import'
const source = `
import { A } from 'a'
import { B } from 'b'

console.log(A)
console.log(B)
`

const file = recma()
  .use({ settings: { module: true } })
  .use(recmaModuleToFunction, { importName })
  .processSync(source)

const AsyncFunction = customImport.constructor

const fn = new AsyncFunction(importName, String(file))
const result = await fn()

Dynamic import

If you use a bundler, it may interpret support relative dynamic imports. For example, you may have a file structure like this:

├── lib
│   └── eval.js
└── modules
    ├── a.js
    └── b.js

Then eval.js could look something like this:

import { recma } from 'recma'
import recmaModuleToFunction from 'recma-module-to-function'

async function customImport(name) {
  return import(`../modules/${name}.js`)
}

const importName = '_import'
const source = `
import { A } from 'a'
import { B } from 'b'

console.log(A)
console.log(B)
`

const file = recma()
  .use({ settings: { module: true } })
  .use(recmaModuleToFunction, { importName })
  .processSync(source)

const AsyncFunction = customImport.constructor

const fn = new AsyncFunction(importName, String(file))
const result = await fn()

CDN

You can define a custom import to resolve imports code to a CDN such as esm.sh. You can even allow import attributes to let the user decide on the CDN.

import { recma } from 'recma'
import recmaModuleToFunction from 'recma-module-to-function'

async function customImport(name, options) {
  return import(`https://esm.sh/${name}`, options)
}

const importName = '_import'
const source = `
import confetti from 'canvas-confetti'

confetti()
`

const file = recma()
  .use({ settings: { module: true } })
  .use(recmaModuleToFunction, { importName })
  .processSync(source)

const AsyncFunction = customImport.constructor

const fn = new AsyncFunction(importName, String(file))
const result = await fn()

MDX with React

This project is compatible with MDX. One of the main goals is to be an alternative strategy to implement MDX on demand.

On the server, you can compile the MDX content with compile(). Then pass the compiled code to a client component.

// app/page.tsx
import { compileSync } from '@mdx-js/mdx'
import { type ReactNode } from 'react'
import recmaModuleToFunction from 'recma-module-to-function'

import { Eval } from '../components/Eval.tsx'

const mdx = `
import { Button } from 'components'

Hello {props.name}!

<Button>Click me!</Button>
`

const code = compileSync(mdx, {
  recmaPlugins: [[recmaModuleToFunction, { importName: '_import' }]]
})

export default function Page(): ReactNode {
  return <Eval code={String(code)} importName={importName} />
}

In the client component, evaluate the code with the AsyncFunction constructor. Use a custom import implementation to explicitly define which modules the code is allowed to access.

// components/Eval.tsx
'use client'

import { type ComponentProps, type ReactNode, useEffect, useState } from 'react'
import * as runtime from 'react/jsx-runtime'
import { type Import } from 'recma-module-to-function'

// Define some components
function Button(props: ComponentProps<'button'>): ReactNode {
  return <button type="button" {...props} />
}

const modules = new Map([
  // Define the `components` module
  ['components', { Button }],
  // Make sure the JSX automatic runtime can be imported.
  ['react/jsx-runtime', runtime]
])

// A custom import implementation which allows importing modules define by our map.
const customImport: Import = async (name) => {
  const module = modules.get(name)
  if (module) {
    return module
  }

  throw new Error(`Module not found '${name}'`)
}

// Grab the AsyncFunction constructor from any async function.
const AsyncFunction = customImport.constructor

interface EvalProps {
  code: string
  importName: string
}

// The client component which can asynchronously render code.
export function Eval({ code, importName }: EvalProps): ReactNode {
  const [content, setContent] = useState<ReactNode>()
  const [error, setError] = useState<unknown>()

  useEffect(() => {
    let cancelled = false

    const fn = new AsyncFunction(importName, code)
    fn(customImport).then(
      ({ default: MDXContent }) => {
        if (!cancelled) {
          setContent(<MDXContent name="User" />)
          setError()
        }
      },
      (err) => {
        if (!cancelled) {
          setContent(null)
          setError(err)
        }
      }
    )

    return () => {
      cancelled = true
    }
  }, [code, importName])

  if (error !== undefined) {
    throw error
  }

  return content
}

Security

This package only transforms the AST input, which is safe to use on its own. However, it was created with the use case in mind to evaluate a JavaScript module. Evaluating user input is dangerous and should be avoided.

If you use MDX, consider using a build tool integration such as @mdx-js/loader or @mdx-js/rollup instead.

Compatibility

This project is compatible with Node.js 20 or greater.

License

MIT © Remco Haszing