module: warn on require of .js inside type: module · nodejs/node@2695f82 · GitHub
Skip to content

Commit 2695f82

Browse files
guybedfordtargos
authored andcommitted
module: warn on require of .js inside type: module
PR-URL: #29909 Reviewed-By: Jan Krems <jan.krems@gmail.com> Reviewed-By: Ruben Bridgewater <ruben@bridgewater.de> Reviewed-By: Colin Ihrig <cjihrig@gmail.com>
1 parent 1fefd7f commit 2695f82

4 files changed

Lines changed: 67 additions & 5 deletions

File tree

lib/internal/modules/cjs/loader.js

Lines changed: 27 additions & 5 deletions
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
'use strict';
2+
3+
const common = require('../common');
4+
const fixtures = require('../common/fixtures');
5+
const { spawn } = require('child_process');
6+
const assert = require('assert');
7+
const path = require('path');
8+
9+
const requiring = path.resolve(fixtures.path('/es-modules/cjs-esm.js'));
10+
const required = path.resolve(
11+
fixtures.path('/es-modules/package-type-module/cjs.js')
12+
);
13+
const pjson = path.resolve(
14+
fixtures.path('/es-modules/package-type-module/package.json')
15+
);
16+
17+
const basename = 'cjs.js';
18+
19+
const child = spawn(process.execPath, [requiring]);
20+
let stderr = '';
21+
child.stderr.setEncoding('utf8');
22+
child.stderr.on('data', (data) => {
23+
stderr += data;
24+
});
25+
child.on('close', common.mustCall((code, signal) => {
26+
assert.strictEqual(code, 0);
27+
assert.strictEqual(signal, null);
28+
29+
assert.strictEqual(stderr, `(node:${child.pid}) Warning: ` +
30+
'require() of ES modules is not supported.\nrequire() of ' +
31+
`${required} from ${requiring} ` +
32+
'is an ES module file as it is a .js file whose nearest parent ' +
33+
'package.json contains "type": "module" which defines all .js ' +
34+
'files in that package scope as ES modules.\nInstead rename ' +
35+
`${basename} to end in .cjs, change the requiring code to use ` +
36+
'import(), or remove "type": "module" from ' +
37+
`${pjson}.\n`);
38+
}));
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
require('./package-type-module/cjs.js');
Lines changed: 1 addition & 0 deletions

0 commit comments

Comments
 (0)