GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Fix ESM support in Node >= 20. (#4425) · nightwatchjs/nightwatch@e8cf1a8

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • .gitignore
  • lib/utils
    • requireModule.js
  • test/src/utils
    • __data__
      • mixed-exports.mjs
      • named-exports.mjs
    • testRequireModule.js
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎.gitignore‎

Copy file name to clipboardExpand all lines: .gitignore
+1Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,3 +31,4 @@ html-report/
3131
test-results.xml
3232
chromedriver-mobile/
3333
*.sw[po]
34+
snapshot.html
Collapse file

‎lib/utils/requireModule.js‎

Copy file name to clipboardExpand all lines: lib/utils/requireModule.js
+41-28Lines changed: 41 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,47 +1,60 @@
1-
const getNodeVersion = () => {
2-
const version = process.version.replace('v', '');
3-
4-
return parseInt(version, 10);
1+
const mergeDefaultAndNamedExports = (module) => {
2+
const _default = module.default || {};
3+
return Object.keys(module).reduce((prev, val) => {
4+
if (val !== 'default') {
5+
prev[val] = module[val];
6+
}
7+
8+
return prev;
9+
}, _default);
510
}
611

12+
/**
13+
* Requires a module, supporting both CommonJS and ES6 modules.
14+
*
15+
* @param {string} fullpath - The full path to the module to require.
16+
* @returns {any|Promise<any>} - The required module or a promise that resolves to the required module.
17+
*/
718
module.exports = function (fullpath) {
819
let exported;
920
try {
1021
exported = require(fullpath);
1122
} catch (err) {
12-
if (err.message === 'Cannot use import statement outside a module' || err.message === 'Unexpected token \'export\'') {
23+
const isEsmSyntaxError = err.message === 'Cannot use import statement outside a module' ||
24+
err.message.includes('Unexpected token \'export\'');
25+
const isMjsFile = fullpath.endsWith('.mjs');
26+
27+
// calling require() on a .mjs file on Node.js < 20 throws ERR_REQUIRE_ESM.
28+
// calling require() on a .mjs file on Node.js >= 20 passes through without
29+
// any error, but if ts-node is activated, it throws ERR_REQUIRE_ESM in normal
30+
// cases (it still relies on the old CommonJS loader) and isEsmSyntaxError if
31+
// v8-compile-cache-lib is used (see PR #4437).
32+
// Use dynamic import() in both cases.
33+
if (err.code === 'ERR_REQUIRE_ESM' || (isMjsFile && isEsmSyntaxError)) {
34+
const { pathToFileURL } = require('node:url');
35+
36+
return import(pathToFileURL(fullpath).href).then(mergeDefaultAndNamedExports);
37+
}
38+
39+
if (isEsmSyntaxError) {
1340
err.detailedErr = err.message;
1441
err.help = ['Using ES6 import/export syntax? - make sure to specify "type=module" in your package.json or use .mjs extension.'];
1542
err.link = 'https://nodejs.org/api/esm.html';
16-
17-
throw err;
1843
}
1944

20-
if (err.code !== 'ERR_REQUIRE_ESM') {
21-
throw err;
22-
}
23-
24-
if (getNodeVersion() >= 14) {
25-
const {pathToFileURL} = require('node:url');
26-
27-
return import(pathToFileURL(fullpath).href).then(result => {
28-
const _default = result.default || {};
29-
30-
return Object.keys(result).reduce((prev, val) => {
31-
if (val !== 'default') {
32-
prev[val] = result[val];
33-
}
45+
throw err;
46+
}
3447

35-
return prev;
36-
}, _default);
37-
});
48+
if (exported && Object.prototype.hasOwnProperty.call(exported, 'default')) {
49+
const keys = Object.keys(exported);
50+
if (keys.length === 1 || (keys.length === 2 && exported.__esModule === true)) {
51+
return exported.default;
3852
}
39-
40-
return import(fullpath).then(result => (result.default || {}));
4153
}
4254

43-
if (exported && Object.prototype.hasOwnProperty.call(exported, 'default') && Object.keys(exported).length === 1) {
44-
return exported.default;
55+
if (exported?.__esModule === true) {
56+
// ESM module with named exports present (with or without default export).
57+
return mergeDefaultAndNamedExports(exported);
4558
}
4659

4760
return exported;
Collapse file

‎test/src/utils/__data__/mixed-exports.mjs‎

Copy file name to clipboard
+12Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
const defaultExport = {
2+
defaultValue: 'default-value',
3+
defaultFunction: function() {
4+
return 'default function called';
5+
}
6+
};
7+
8+
export default defaultExport;
9+
export const namedExport = 'named value';
10+
export const namedFunction = function() {
11+
return 'named function called';
12+
};
Collapse file

‎test/src/utils/__data__/named-exports.mjs‎

Copy file name to clipboard
+2Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
export const functionA = () => 'A';
2+
export const functionB = () => 'B';
Collapse file

‎test/src/utils/testRequireModule.js‎

Copy file name to clipboardExpand all lines: test/src/utils/testRequireModule.js
+33Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,4 +18,37 @@ describe('test requireModule', function () {
1818

1919
assert.equal(meaningOfLife, 42);
2020
});
21+
22+
it('should load es6 module with ts-node activated', async function () {
23+
const tsNode = require('ts-node').register({
24+
project: path.resolve('test', './tsconfig.json')
25+
});
26+
27+
const modulePath = path.join(__dirname, './__data__/meaning-of-life.mjs');
28+
// delete from cache to force reloading
29+
delete require.cache[require.resolve(modulePath)];
30+
31+
const meaningOfLife = await requireModule(modulePath);
32+
33+
assert.equal(meaningOfLife, 42);
34+
tsNode.enabled(false);
35+
});
36+
37+
it('should load named exports from .mjs file', async function () {
38+
const modulePath = path.join(__dirname, './__data__/named-exports.mjs');
39+
const module = await requireModule(modulePath);
40+
41+
assert.equal(typeof module.functionA, 'function');
42+
assert.equal(typeof module.functionB, 'function');
43+
});
44+
45+
it('should load default and named exports from .mjs file', async function () {
46+
const modulePath = path.join(__dirname, '__data__/mixed-exports.mjs');
47+
const module = await requireModule(modulePath);
48+
49+
assert.equal(module.defaultValue, 'default-value');
50+
assert.equal(module.defaultFunction(), 'default function called');
51+
assert.equal(module.namedExport, 'named value');
52+
assert.equal(module.namedFunction(), 'named function called');
53+
});
2154
});

0 commit comments

Comments
0 (0)
You are visitor 01402622 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.