Skip to content

Commit

Permalink
lib,test: print CJS suggestions when ES not found
Browse files Browse the repository at this point in the history
  • Loading branch information
juanarbol committed Dec 26, 2019
1 parent 49dc514 commit 3e23195
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 3 deletions.
31 changes: 30 additions & 1 deletion lib/internal/modules/esm/default_resolve.js
Expand Up @@ -9,6 +9,10 @@ const { NativeModule } = require('internal/bootstrap/loaders');
const { extname } = require('path');
const { realpathSync } = require('fs');
const { getOptionValue } = require('internal/options');
const {
Module: CJSModule
} = require('internal/modules/cjs/loader');


const preserveSymlinks = getOptionValue('--preserve-symlinks');
const preserveSymlinksMain = getOptionValue('--preserve-symlinks-main');
Expand Down Expand Up @@ -93,7 +97,32 @@ function resolve(specifier, parentURL) {
throw new ERR_INPUT_TYPE_NOT_ALLOWED();
}

let url = moduleWrapResolve(specifier, parentURL);
let url;
try {
url = moduleWrapResolve(specifier, parentURL);
} catch (error) {
try {
// By default ES Modules does not support extensionless files.
// The idea is make suggestions when file ext is not provided
// Example: import pkg from './meow'
// Ref: https://github.com/nodejs/node/issues/30603

// Create a fake CJS Module using parentURL.
const currentModule = new CJSModule(parentURL);
// Resolve our especifier e.g: 'file'
// using as module parent our current module.
// So with our fake parent, paths to search in CJS will be provided.
const cjsResolved = CJSModule._resolveFilename(specifier,
currentModule,
false);
if (cjsResolved) {
error.message += '\nCJS would resolved: ' + cjsResolved;
}
} catch (cjsError) { // eslint-disable-line no-unused-vars
// ignore
}
throw error;
}

if (isMain ? !preserveSymlinksMain : !preserveSymlinks) {
const real = realpathSync(fileURLToPath(url), {
Expand Down
4 changes: 4 additions & 0 deletions test/es-module/test-esm-cjs-loader-suggestions.mjs
@@ -0,0 +1,4 @@
import '../common/index.mjs';

import('../fixtures/es-modules/cjs')
.catch(err => console.error(err))
4 changes: 2 additions & 2 deletions test/message/esm_loader_not_found.out
@@ -1,8 +1,8 @@
(node:*) ExperimentalWarning: The ESM module loader is experimental.
(node:*) ExperimentalWarning: --experimental-loader is an experimental feature. This feature could change at any time
internal/modules/esm/default_resolve.js:*
let url = moduleWrapResolve(specifier, parentURL);
^
url = moduleWrapResolve(specifier, parentURL);
^

Error: Cannot find package 'i-dont-exist' imported from *
at Loader.resolve [as _resolve] (internal/modules/esm/default_resolve.js:*:*)
Expand Down

0 comments on commit 3e23195

Please sign in to comment.