-
-
Notifications
You must be signed in to change notification settings - Fork 528
Expand file tree
/
Copy pathimport-helper.js
More file actions
57 lines (51 loc) · 1.4 KB
/
import-helper.js
File metadata and controls
57 lines (51 loc) · 1.4 KB
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
56
57
import url from 'url';
async function supportsDynamicImport() {
try {
// imports are cached.
// no need to worry about perf here.
// Don't remove .js: extension must be included for ESM imports!
await import('./dummy-file.js');
return true;
} catch (e) {
return false;
}
}
function isPackageInstalled(packageName) {
try {
// Try to require the package
require.resolve(packageName);
return true;
} catch (error) {
// If require.resolve throws an error, the package is not installed
return false;
}
}
const isTypescriptProject = isPackageInstalled('typescript');
/**
* Imports a JSON, CommonJS or ESM module
* based on feature detection.
*
* @param modulePath path to the module to import
* @returns {Promise<unknown>} the imported module.
*/
async function importModule(modulePath) {
// JSON modules are still behind a flag. Fallback to require for now.
// https://nodejs.org/api/esm.html#json-modules
if (
url.pathToFileURL &&
!modulePath.endsWith('.json') &&
(await supportsDynamicImport())
) {
// 'import' expects a URL. (https://github.com/sequelize/cli/issues/994)
return import(url.pathToFileURL(modulePath));
}
// mimics what `import()` would return for
// cjs modules.
return { default: require(modulePath) };
}
module.exports = {
supportsDynamicImport,
importModule,
isPackageInstalled,
isTypescriptProject,
};