Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

doc: update experimental loader hooks example code #29373

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 19 additions & 5 deletions doc/api/esm.md
Original file line number Diff line number Diff line change
Expand Up @@ -573,8 +573,14 @@ The resolve hook returns the resolved file URL and module format for a
given module specifier and parent file URL:

```js
const baseURL = new URL(`${process.cwd()}/`, 'file://');

import { URL, pathToFileURL } from 'url';
const baseURL = pathToFileURL(process.cwd()).href;

/**
* @param {string} specifier
* @param {string} parentModuleURL
* @param {function} defaultResolver
*/
export async function resolve(specifier,
parentModuleURL = baseURL,
defaultResolver) {
Expand Down Expand Up @@ -612,13 +618,21 @@ be written:
import path from 'path';
import process from 'process';
import Module from 'module';
import { URL, pathToFileURL } from 'url';

const builtins = Module.builtinModules;
const JS_EXTENSIONS = new Set(['.js', '.mjs']);

const baseURL = new URL(`${process.cwd()}/`, 'file://');
const baseURL = pathToFileURL(process.cwd()).href;

export function resolve(specifier, parentModuleURL = baseURL, defaultResolve) {
/**
* @param {string} specifier
* @param {string} parentModuleURL
* @param {function} defaultResolver
*/
export async function resolve(specifier,
parentModuleURL = baseURL,
defaultResolver) {
if (builtins.includes(specifier)) {
return {
url: specifier,
Expand All @@ -627,7 +641,7 @@ export function resolve(specifier, parentModuleURL = baseURL, defaultResolve) {
}
if (/^\.{0,2}[/]/.test(specifier) !== true && !specifier.startsWith('file:')) {
// For node_modules support:
// return defaultResolve(specifier, parentModuleURL);
// return defaultResolver(specifier, parentModuleURL);
throw new Error(
`imports must begin with '/', './', or '../'; '${specifier}' does not`);
}
Expand Down