Use the Code Snippet WebPart in SharePoint pages
Modern SharePoint is great
Modern SharePoint has myriad improvements to its user interface compared to the old Classic versions, e.g. SharePoint 2013. You can easily insert a wide range of excellent out-of-the-box WebParts into your pages to provide amazing functionality, or simply craft a beautiful looking web page. The Text WebPart however is fairly limited in its formatting options, and requires some imagination and creativity for anything more than plain text.
The Code Snippet WebPart
Insert a Code Snippet from the WebPart Selector. Probably better to place it in a 2/3 or full column width area.
Then simply copy and paste a single line of code — or many lines — into the WebPart, and it will format and beautify with full syntax colouring. The colouring options appear similar to Visual Studio Code.