-
-
Notifications
You must be signed in to change notification settings - Fork 618
Expand file tree
/
Copy pathreplaceCoreImports.js
More file actions
39 lines (33 loc) · 1.28 KB
/
replaceCoreImports.js
File metadata and controls
39 lines (33 loc) · 1.28 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
const CORE_ESM_IMPORT_PATTERN = /(from|import)\s+["'](#core(.*?))["'](;)?/gm
const CORE_CJS_IMPORT_PATTERN = /require\(["'](#core(.*?))["']\)(;)?/gm
function getCoreImportPattern(isEsm) {
return isEsm ? CORE_ESM_IMPORT_PATTERN : CORE_CJS_IMPORT_PATTERN
}
export function hasCoreImports(fileContents, isEsm) {
return fileContents.search(getCoreImportPattern(isEsm)) !== -1
}
export function replaceCoreImports(moduleFilePath, fileContents, isEsm) {
if (isEsm) {
return fileContents.replace(
CORE_ESM_IMPORT_PATTERN,
(_, keyword, __, maybeSubmodulePath, maybeSemicolon) => {
const submodulePath = maybeSubmodulePath || '/index'
/**
* @note Although all .d.ts are considered ESM, append different
* file extension for d.mts files.
*/
const extension = moduleFilePath.endsWith('.d.mts') ? '.mjs' : ''
const semicolon = maybeSemicolon || ''
return `${keyword} "../core${submodulePath}${extension}"${semicolon}`
},
)
}
return fileContents.replace(
CORE_CJS_IMPORT_PATTERN,
(_, __, maybeSubmodulePath, maybeSemicolon) => {
const submodulePath = maybeSubmodulePath || '/index'
const semicolon = maybeSemicolon || ''
return `require("../core${submodulePath}")${semicolon}`
},
)
}