summaryrefslogtreecommitdiff
path: root/test/es-module/test-cjs-esm-warn.js
blob: b800a47d0515d54ed305576d87082271d39900a9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
'use strict';

const common = require('../common');
const fixtures = require('../common/fixtures');
const { spawn } = require('child_process');
const assert = require('assert');
const path = require('path');

const requiring = path.resolve(fixtures.path('/es-modules/cjs-esm.js'));
const required = path.resolve(
  fixtures.path('/es-modules/package-type-module/cjs.js')
);
const pjson = path.resolve(
  fixtures.path('/es-modules/package-type-module/package.json')
);

const basename = 'cjs.js';

const child = spawn(process.execPath, [requiring]);
let stderr = '';
child.stderr.setEncoding('utf8');
child.stderr.on('data', (data) => {
  stderr += data;
});
child.on('close', common.mustCall((code, signal) => {
  assert.strictEqual(code, 1);
  assert.strictEqual(signal, null);

  assert.ok(stderr.indexOf(
    `Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: ${required}` +
    '\nrequire() of ES modules is not supported.\nrequire() of ' +
    `${required} from ${requiring} ` +
    'is an ES module file as it is a .js file whose nearest parent ' +
    'package.json contains "type": "module" which defines all .js ' +
    'files in that package scope as ES modules.\nInstead rename ' +
    `${basename} to end in .cjs, change the requiring code to use ` +
    'import(), or remove "type": "module" from ' +
    `${pjson}.\n`) !== -1);
  assert.ok(stderr.indexOf(
    'Error [ERR_REQUIRE_ESM]: Must use import to load ES Module') !== -1);

  assert.strictEqual(
    stderr.match(/Must use import to load ES Module/g).length, 1);
}));