forked from babel/babel
/
get-module-name.ts
80 lines (66 loc) 路 2 KB
/
get-module-name.ts
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
type RootOptions = {
filename?: string;
filenameRelative?: string;
sourceRoot?: string;
};
export type PluginOptions = {
moduleId?: string;
moduleIds?: boolean;
getModuleId?: (moduleName: string) => string | null | undefined;
moduleRoot?: string;
};
if (!process.env.BABEL_8_BREAKING) {
const originalGetModuleName = getModuleName;
// @ts-expect-error TS doesn't like reassigning a function.
// eslint-disable-next-line no-func-assign
getModuleName = function getModuleName(
rootOpts: RootOptions & PluginOptions,
pluginOpts: PluginOptions,
): string | null {
return originalGetModuleName(rootOpts, {
moduleId: pluginOpts.moduleId ?? rootOpts.moduleId,
moduleIds: pluginOpts.moduleIds ?? rootOpts.moduleIds,
getModuleId: pluginOpts.getModuleId ?? rootOpts.getModuleId,
moduleRoot: pluginOpts.moduleRoot ?? rootOpts.moduleRoot,
});
};
}
export default function getModuleName(
rootOpts: RootOptions,
pluginOpts: PluginOptions,
): string | null {
const {
filename,
filenameRelative = filename,
sourceRoot = pluginOpts.moduleRoot,
} = rootOpts;
const {
moduleId,
moduleIds = !!moduleId,
getModuleId,
moduleRoot = sourceRoot,
} = pluginOpts;
if (!moduleIds) return null;
// moduleId is n/a if a `getModuleId()` is provided
if (moduleId != null && !getModuleId) {
return moduleId;
}
let moduleName = moduleRoot != null ? moduleRoot + "/" : "";
if (filenameRelative) {
const sourceRootReplacer =
sourceRoot != null ? new RegExp("^" + sourceRoot + "/?") : "";
moduleName += filenameRelative
// remove sourceRoot from filename
.replace(sourceRootReplacer, "")
// remove extension
.replace(/\.(\w*?)$/, "");
}
// normalize path separators
moduleName = moduleName.replace(/\\/g, "/");
if (getModuleId) {
// If return is falsy, assume they want us to use our generated default name
return getModuleId(moduleName) || moduleName;
} else {
return moduleName;
}
}