| 1 |
type RootOptions = { |
| 2 |
filename?: string; |
| 3 |
filenameRelative?: string; |
| 4 |
sourceRoot?: string; |
| 5 |
}; |
| 6 |
|
| 7 |
export type PluginOptions = { |
| 8 |
moduleId?: string; |
| 9 |
moduleIds?: boolean; |
| 10 |
getModuleId?: (moduleName: string) => string | null | undefined; |
| 11 |
moduleRoot?: string; |
| 12 |
}; |
| 13 |
|
| 14 |
if (!process.env.BABEL_8_BREAKING) { |
| 15 |
const originalGetModuleName = getModuleName; |
| 16 |
|
| 17 |
// @ts-expect-error TS doesn't like reassigning a function. |
| 18 |
// eslint-disable-next-line no-func-assign |
| 19 |
getModuleName = function getModuleName( |
| 20 |
rootOpts: RootOptions & PluginOptions, |
| 21 |
pluginOpts: PluginOptions, |
| 22 |
): string | null { |
| 23 |
return originalGetModuleName(rootOpts, { |
| 24 |
moduleId: pluginOpts.moduleId ?? rootOpts.moduleId, |
| 25 |
moduleIds: pluginOpts.moduleIds ?? rootOpts.moduleIds, |
| 26 |
getModuleId: pluginOpts.getModuleId ?? rootOpts.getModuleId, |
| 27 |
moduleRoot: pluginOpts.moduleRoot ?? rootOpts.moduleRoot, |
| 28 |
}); |
| 29 |
}; |
| 30 |
} |
| 31 |
|
| 32 |
export default function getModuleName( |
| 33 |
rootOpts: RootOptions, |
| 34 |
pluginOpts: PluginOptions, |
| 35 |
): string | null { |
| 36 |
const { |
| 37 |
filename, |
| 38 |
filenameRelative = filename, |
| 39 |
sourceRoot = pluginOpts.moduleRoot, |
| 40 |
} = rootOpts; |
| 41 |
|
| 42 |
const { |
| 43 |
moduleId, |
| 44 |
moduleIds = !!moduleId, |
| 45 |
|
| 46 |
getModuleId, |
| 47 |
|
| 48 |
moduleRoot = sourceRoot, |
| 49 |
} = pluginOpts; |
| 50 |
|
| 51 |
if (!moduleIds) return null; |
| 52 |
|
| 53 |
// moduleId is n/a if a `getModuleId()` is provided |
| 54 |
if (moduleId != null && !getModuleId) { |
| 55 |
return moduleId; |
| 56 |
} |
| 57 |
|
| 58 |
let moduleName = moduleRoot != null ? moduleRoot + "/" : ""; |
| 59 |
|
| 60 |
if (filenameRelative) { |
| 61 |
const sourceRootReplacer = |
| 62 |
sourceRoot != null ? new RegExp("^" + sourceRoot + "/?") : ""; |
| 63 |
|
| 64 |
moduleName += filenameRelative |
| 65 |
// remove sourceRoot from filename |
| 66 |
.replace(sourceRootReplacer, "") |
| 67 |
// remove extension |
| 68 |
.replace(/\.(\w*?)$/, ""); |
| 69 |
} |
| 70 |
|
| 71 |
// normalize path separators |
| 72 |
moduleName = moduleName.replace(/\\/g, "/"); |
| 73 |
|
| 74 |
if (getModuleId) { |
| 75 |
// If return is falsy, assume they want us to use our generated default name |
| 76 |
return getModuleId(moduleName) || moduleName; |
| 77 |
} else { |
| 78 |
return moduleName; |
| 79 |
} |
| 80 |
} |