({
assets,
inlineMarkdownAssetImageFileLoader,
}: {
assets: unknown;
inlineMarkdownAssetImageFileLoader: string;
})
| 21 | * `{image: "./myImage.png"}` => `{image: require("./myImage.png")}` |
| 22 | */ |
| 23 | export function createAssetsExportCode({ |
| 24 | assets, |
| 25 | inlineMarkdownAssetImageFileLoader, |
| 26 | }: { |
| 27 | assets: unknown; |
| 28 | inlineMarkdownAssetImageFileLoader: string; |
| 29 | }): string { |
| 30 | if ( |
| 31 | typeof assets !== 'object' || |
| 32 | !assets || |
| 33 | Object.keys(assets).length === 0 |
| 34 | ) { |
| 35 | return 'undefined'; |
| 36 | } |
| 37 | |
| 38 | // TODO implementation can be completed/enhanced |
| 39 | function createAssetValueCode(assetValue: unknown): string | undefined { |
| 40 | if (Array.isArray(assetValue)) { |
| 41 | const arrayItemCodes = assetValue.map( |
| 42 | (item: unknown) => createAssetValueCode(item) ?? 'undefined', |
| 43 | ); |
| 44 | return `[${arrayItemCodes.join(', ')}]`; |
| 45 | } |
| 46 | // Only process string values starting with ./ |
| 47 | // We could enhance this logic and check if file exists on disc? |
| 48 | if (typeof assetValue === 'string' && assetValue.startsWith('./')) { |
| 49 | // TODO do we have other use-cases than image assets? |
| 50 | // Probably not worth adding more support, as we want to move to Webpack 5 new asset system (https://github.com/facebook/docusaurus/pull/4708) |
| 51 | return `require("${inlineMarkdownAssetImageFileLoader}${escapePath( |
| 52 | assetValue, |
| 53 | )}").default`; |
| 54 | } |
| 55 | return undefined; |
| 56 | } |
| 57 | |
| 58 | const assetEntries = Object.entries(assets); |
| 59 | |
| 60 | const codeLines = assetEntries |
| 61 | .map(([key, value]: [string, unknown]) => { |
| 62 | const assetRequireCode = createAssetValueCode(value); |
| 63 | return assetRequireCode ? `"${key}": ${assetRequireCode},` : undefined; |
| 64 | }) |
| 65 | .filter(Boolean); |
| 66 | |
| 67 | return `{\n${codeLines.join('\n')}\n}`; |
| 68 | } |
| 69 | |
| 70 | /** |
| 71 | * data.contentTitle is set by the remark contentTitle plugin |
no test coverage detected
searching dependent graphs…