Skip to content

Commit

Permalink
fix(swagger-ui): Implement multiple js and css imports
Browse files Browse the repository at this point in the history
Accept arrays in addition to single URLs in SwaggerCustomOptions to be able to include more than one external JS file.
  • Loading branch information
lukas-reining committed Nov 5, 2022
1 parent be01469 commit b9483ad
Show file tree
Hide file tree
Showing 3 changed files with 13,663 additions and 54 deletions.
6 changes: 3 additions & 3 deletions lib/interfaces/swagger-custom-options.interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ export interface SwaggerCustomOptions {
explorer?: boolean;
swaggerOptions?: SwaggerUiOptions;
customCss?: string;
customCssUrl?: string;
customJs?: string;
customJsStr?: string;
customCssUrl?: string | string[];
customJs?: string | string[];
customJsStr?: string | string[];
customfavIcon?: string;
swaggerUrl?: string;
customSiteTitle?: string;
Expand Down
39 changes: 31 additions & 8 deletions lib/swagger-ui/swagger-ui.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,33 @@ export function getSwaggerAssetsAbsoluteFSPath() {
return swaggerAssetsAbsoluteFSPath;
}

function toExternalScriptTag(url: string) {
return `<script src='${url}'></script>`;
}

function toInlineScriptTag(url: string) {
return `<script> ${url} </script>`;
}

function toExternalStylesheetTag(url: string) {
return `<link href='${url}' rel='stylesheet'>`;
}

function toTags(
customCode: string | string[] | undefined,
toScript: (url: string) => string
) {
if (!customCode) {
return '';
}

if (typeof customCode === 'string') {
return toScript(customCode);
} else {
return customCode.map(toScript).join('\n');
}
}

/**
* Used to build swagger-ui custom html
*/
Expand All @@ -53,7 +80,7 @@ export function buildSwaggerHTML(
} = customOptions;

const favIconString = customfavIcon
? `<link rel="icon" href="${customfavIcon}" />`
? `<link rel='icon' href='${customfavIcon}' />`
: favIconHtml;

const explorerCss = explorer
Expand All @@ -64,15 +91,11 @@ export function buildSwaggerHTML(
.replace('<% explorerCss %>', explorerCss)
.replace('<% favIconString %>', favIconString)
.replace(/<% baseUrl %>/g, baseUrl)
.replace(
'<% customJs %>',
customJs ? `<script src="${customJs}"></script>` : ''
)
.replace(
'<% customJsStr %>', customJsStr ? `<script> ${customJsStr} </script>` : '')
.replace('<% customJs %>', toTags(customJs, toExternalScriptTag))
.replace('<% customJsStr %>', toTags(customJsStr, toInlineScriptTag))
.replace(
'<% customCssUrl %>',
customCssUrl ? `<link href="${customCssUrl}" rel="stylesheet">` : ''
toTags(customCssUrl, toExternalStylesheetTag)
)
.replace('<% title %>', customSiteTitle);
}
Loading

0 comments on commit b9483ad

Please sign in to comment.