|
| 1 | +const fs = require('fs'); |
| 2 | +const moduleRequire = require('module').createRequire(__dirname); |
| 3 | + |
| 4 | +const PACKAGES_TO_DEDUPE = [ |
| 5 | + '@docusaurus/plugin-content-docs', |
| 6 | + '@docusaurus/theme-common', |
| 7 | + '@docusaurus/theme-search-algolia', |
| 8 | +]; |
| 9 | + |
| 10 | +function getExportKeys(exportsField) { |
| 11 | + if (!exportsField) { |
| 12 | + return ['.']; |
| 13 | + } |
| 14 | + |
| 15 | + if (typeof exportsField === 'string') { |
| 16 | + return ['.']; |
| 17 | + } |
| 18 | + |
| 19 | + if (Array.isArray(exportsField)) { |
| 20 | + return ['.']; |
| 21 | + } |
| 22 | + |
| 23 | + if (typeof exportsField === 'object') { |
| 24 | + const keys = new Set(['.']); |
| 25 | + for (const key of Object.keys(exportsField)) { |
| 26 | + if (key === 'default' || key.includes('*')) { |
| 27 | + continue; |
| 28 | + } |
| 29 | + keys.add(key); |
| 30 | + } |
| 31 | + return Array.from(keys); |
| 32 | + } |
| 33 | + |
| 34 | + return ['.']; |
| 35 | +} |
| 36 | + |
| 37 | +function normalizeSubpath(pkgName, subpath) { |
| 38 | + if (subpath === '.' || !subpath) { |
| 39 | + return pkgName; |
| 40 | + } |
| 41 | + return `${pkgName}/${subpath.replace(/^\.\//, '')}`; |
| 42 | +} |
| 43 | + |
| 44 | +function buildAliasesForPackage(pkgName) { |
| 45 | + let pkgJsonPath; |
| 46 | + try { |
| 47 | + pkgJsonPath = moduleRequire.resolve(`${pkgName}/package.json`); |
| 48 | + } catch (error) { |
| 49 | + console.warn( |
| 50 | + `docusaurus-dedupe-aliases: unable to resolve ${pkgName}`, |
| 51 | + error |
| 52 | + ); |
| 53 | + return []; |
| 54 | + } |
| 55 | + |
| 56 | + const pkgJson = JSON.parse(fs.readFileSync(pkgJsonPath, 'utf8')); |
| 57 | + const exportKeys = getExportKeys(pkgJson.exports); |
| 58 | + |
| 59 | + return exportKeys.flatMap((subpath) => { |
| 60 | + const specifier = normalizeSubpath(pkgName, subpath); |
| 61 | + try { |
| 62 | + const target = moduleRequire.resolve(specifier); |
| 63 | + const aliasKey = |
| 64 | + subpath === '.' ? `${pkgName}$` : specifier.replace(/\\/g, '/'); |
| 65 | + return [[aliasKey, target]]; |
| 66 | + } catch (error) { |
| 67 | + console.warn( |
| 68 | + `docusaurus-dedupe-aliases: unable to resolve specifier ${specifier}`, |
| 69 | + error |
| 70 | + ); |
| 71 | + return []; |
| 72 | + } |
| 73 | + }); |
| 74 | +} |
| 75 | + |
| 76 | +module.exports = function docusaurusDedupeAliases() { |
| 77 | + const aliasEntries = PACKAGES_TO_DEDUPE.flatMap(buildAliasesForPackage); |
| 78 | + const aliases = Object.fromEntries(aliasEntries); |
| 79 | + |
| 80 | + return { |
| 81 | + name: 'docusaurus-dedupe-aliases', |
| 82 | + configureWebpack() { |
| 83 | + return { |
| 84 | + resolve: { |
| 85 | + alias: aliases, |
| 86 | + }, |
| 87 | + }; |
| 88 | + }, |
| 89 | + }; |
| 90 | +}; |
0 commit comments