pre code preserves new lines and causes excessive spacing.

CSS should handle that spacing instead. Output the actual code into the pre tag and let CSS margins, padding or even ::before/::after handle the code spacing, not spacing in the HTML that can't be removed without JS