Skip to content

Commit

Permalink
doc: update experimental loader hooks example code
Browse files Browse the repository at this point in the history
It fix 2 issues in provided Loader hooks examples:
1. Original ``new URL(`${process.cwd()}/`, 'file://');``
is not cross-platform, it gives wrong URL on windows
2. Based on `CHECK` in ModuleWrap::Resolve (node 12.9.1,
https://github.com/nodejs/node/blob/v12.9.1/src/module_wrap.cc#L1132)
the 2nd parameter should be a `string`, not an `URL` object

PR-URL: #29373
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: David Carlier <devnexen@gmail.com>
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
  • Loading branch information
zaverden authored and Trott committed Sep 17, 2019
1 parent e2dcbf1 commit 49cf67e
Showing 1 changed file with 19 additions and 5 deletions.
24 changes: 19 additions & 5 deletions doc/api/esm.md
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

0 comments on commit 49cf67e

Please sign in to comment.