diff --git a/packages/server/src/ChunkExtractor.js b/packages/server/src/ChunkExtractor.js index 19ea1107..4f3deba7 100644 --- a/packages/server/src/ChunkExtractor.js +++ b/packages/server/src/ChunkExtractor.js @@ -20,9 +20,13 @@ function getAssets(chunks, getAsset) { return _.uniqBy(_.flatMap(chunks, chunk => getAsset(chunk)), 'url') } -function extraPropsToString(extraProps) { - return Object.keys(extraProps).reduce( - (acc, key) => `${acc} ${key}="${extraProps[key]}"`, +function handleExtraProps(asset, extraProps) { + return typeof extraProps === 'function' ? extraProps(asset) : extraProps +} + +function extraPropsToString(asset, extraProps) { + return Object.entries(handleExtraProps(asset, extraProps)).reduce( + (acc, [key, value]) => `${acc} ${key}="${value}"`, '', ) } @@ -30,7 +34,7 @@ function extraPropsToString(extraProps) { function assetToScriptTag(asset, extraProps) { return `` + }"${extraPropsToString(asset, extraProps)}>` } function assetToScriptElement(asset, extraProps) { @@ -40,7 +44,7 @@ function assetToScriptElement(asset, extraProps) { async data-chunk={asset.chunk} src={asset.url} - {...extraProps} + {...handleExtraProps(asset, extraProps)} /> ) } @@ -60,7 +64,7 @@ function assetToStyleString(asset) { function assetToStyleTag(asset, extraProps) { return `` + }"${extraPropsToString(asset, extraProps)}>` } function assetToStyleTagInline(asset, extraProps) { @@ -72,6 +76,7 @@ function assetToStyleTagInline(asset, extraProps) { } resolve( ` +" +`), + ) + }) }) describe('#getStyleElements', () => { @@ -309,7 +390,7 @@ Array [ `) }) - it('should add extraProps if specified', () => { + it('should add extraProps if specified - object argument', () => { extractor.addChunk('letters-A') expect(extractor.getStyleElements({ nonce: 'testnonce' })) .toMatchInlineSnapshot(` @@ -327,6 +408,27 @@ Array [ rel="stylesheet" />, ] +`) + }) + + it('should add extraProps if specified - function argument', () => { + extractor.addChunk('letters-A') + expect(extractor.getStyleElements(asset => ({ nonce: asset.chunk }))) + .toMatchInlineSnapshot(` +Array [ + , + , +] `) }) }) @@ -417,7 +519,7 @@ body { `) }) - it('should add extraProps if specified', () => { + it('should add extraProps if specified - object argument', () => { extractor.addChunk('letters-A') expect(extractor.getLinkTags({ nonce: 'testnonce' })) .toMatchInlineSnapshot(` @@ -427,6 +529,19 @@ body { " +`) + }) + + it('should add extraProps if specified - function argument', () => { + extractor.addChunk('letters-A') + expect(extractor.getLinkTags(asset => ({ nonce: asset.chunk }))) + .toMatchInlineSnapshot(` +" + + + + +" `) }) }) diff --git a/website/src/pages/docs/api-loadable-server.mdx b/website/src/pages/docs/api-loadable-server.mdx index 1aff3f8f..e5bf72fe 100644 --- a/website/src/pages/docs/api-loadable-server.mdx +++ b/website/src/pages/docs/api-loadable-server.mdx @@ -58,9 +58,9 @@ const app = Get scripts as a string of `