-
-
Notifications
You must be signed in to change notification settings - Fork 71
/
req.js
40 lines (35 loc) · 974 Bytes
/
req.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
// @ts-check
const { createRequire } = require('node:module')
const { pathToFileURL } = require('node:url')
const TS_EXT_RE = /\.(c|m)?ts$/
/** @type {import('jiti').default | null} */
let jiti = null
/**
* @param {string} name
* @param {string} rootFile
* @returns {Promise<any>}
*/
async function req(name, rootFile = __filename) {
let __require = createRequire(rootFile)
let url = __require.resolve(name)
try {
return (await import(pathToFileURL(url).href)).default
} catch (err) {
if (!TS_EXT_RE.test(url)) {
/* c8 ignore start */
throw err
}
if (!jiti) {
try {
jiti = (await import('jiti')).default
} catch (jitiErr) {
throw new Error(
`'jiti' is required for the TypeScript configuration files. Make sure it is installed\nError: ${jitiErr.message}`
)
}
/* c8 ignore stop */
}
return jiti(rootFile, { interopDefault: true })(name)
}
}
module.exports = req