-
Notifications
You must be signed in to change notification settings - Fork 31.1k
/
Copy pathutils.js
55 lines (49 loc) · 1.74 KB
/
utils.js
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
45
46
47
48
49
50
51
52
53
54
55
'use strict';
const {
ObjectCreate,
StringPrototypeEndsWith,
} = primordials;
const { getOptionValue } = require('internal/options');
function shouldUseESMLoader(filePath) {
/**
* @type {string[]} userLoaders A list of custom loaders registered by the user
* (or an empty list when none have been registered).
*/
const userLoaders = getOptionValue('--experimental-loader');
/**
* @type {string[]} userImports A list of preloaded modules registered by the user
* (or an empty list when none have been registered).
*/
const userImports = getOptionValue('--import');
if (userLoaders.length > 0 || userImports.length > 0)
return true;
// Determine the module format of the main
if (filePath && StringPrototypeEndsWith(filePath, '.mjs'))
return true;
if (!filePath || StringPrototypeEndsWith(filePath, '.cjs'))
return false;
const { readPackageScope } = require('internal/modules/cjs/loader');
const pkg = readPackageScope(filePath);
return pkg?.data?.type === 'module';
}
/**
* @param {string} filePath
* @returns {any}
* requireOrImport imports a module if the file is an ES module, otherwise it requires it.
*/
function requireOrImport(filePath) {
const useESMLoader = shouldUseESMLoader(filePath);
if (useESMLoader) {
const { esmLoader } = require('internal/process/esm_loader');
const { pathToFileURL } = require('internal/url');
const { isAbsolute } = require('path');
const file = isAbsolute(filePath) ? pathToFileURL(filePath).href : filePath;
return esmLoader.import(file, undefined, ObjectCreate(null));
}
const { Module } = require('internal/modules/cjs/loader');
return new Module._load(filePath, null, false);
}
module.exports = {
shouldUseESMLoader,
requireOrImport,
};