nodejs / nodejs/node

Expose the default module resolver in a package

Open
#49,454 4 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

esm module never-stale
Dominant language
JavaScript
Stars
122k
Forks
37.3k
Avg merge
4d 2h
Merged PRs (30d)
283

Description

Currently we can access the default resolver when in a --loader loader. However we can't access this loader from a regular program. I'd like to propose exposing this function as a regular function that can be imported at runtime for use with vm.SourceTextModule to create in-process loaders.

For example:

import vm from 'vm';
import process from 'process';
import url from 'url';
import { resolver } from 'module';

const cwd = url.pathToFileURL(process.cwd() + '/');

class TestLoader {
  #cache = new Map();
  #realm = vm.createContext({});

  async #loadModule(url) {
    return new vm.SourceTextModule(await fsp.readFile(resolvedUrl, 'utf8'), {
      url: resolvedUrl,
      context: this.#realm,
    });
  }
  
  async #linker(module, specifier) {
    // --- Use node's resolution algorithm ---
    const resolvedUrl = resolver(module.url, specifier);
    if (this.#cache.has(resolvedUrl)) {
      return this.#cache.get(resolvedUrl);
    }
    const module = this.#loadModule(resolvedUrl);
    this.#cache.set(resolvedUrl, module);
    return module;
  }

  constructor() {
    // Setup test environment
    this.#realm.evaluate(`function deepEqual(a, b) { /* ... */ }`);
  }

  async runTest(file) {
    const module = this.#loadModule(resolver(cwd, file));
    await module.link((...args) => this.#linker(...args));
    module.instantiate();
    try {
      await module.evaluate();
      return { passed: true };
    } catch (error) {
      return { passed: false, error };
    }
  }
}

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reviewing the existing resolver available to --loader loaders and the vm.SourceTextModule linking flow shown in the example. Determine the runtime API and module entry point needed to import the default resolver, then verify that it supports in-process loader resolution as demonstrated.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, node.js
Domain
backend
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.