Incumbent party candidate Mr Moreno won 51.16% of the vote, the country's electoral council announced.
Conservative Guillermo Lasso, whom three exit polls predicted would win after the vote on Sunday, got 48.8%.
Mr Lasso has already indicated he will challenge the vote, having earlier alleged fraud.
But with 99.65% of ballots counted, the National Electoral Council's Pablo Pozo said these were the "irreversible official results".
"We congratulate the Ecuadoran people, who have legally and legitimately elected their president," he said.
"Ecuador has spoken freely at the ballot box and it is our ethical duty to respect its vote and its voice."
After the announcement, Mr Moreno tweeted: "Many thanks to all Ecuadorians, who voted for us and who did not, and democracy is strengthened."
Correspondents say his win bucks the trend across Latin America of people turning their backs on the left in favour of the right.
He succeeds his close ally Rafael Correa after three terms of what Mr Correa and his administration dubbed "21st-Century socialism".
On Sunday, when it first emerged he looked likely to lose, Mr Lasso called for people to "peacefully defend their votes".
It resulted in hundreds of Mr Lasso's supporters gathering in front of the electoral commission offices shouting "No to fraud".
The Organization of American States, which acted as an observer during the election, said it had seen "no discrepancies" between polling station and official results.
Mr Lasso has until 12 April to challenge the result officially, the electoral council said.
Socialist Lenin Moreno has been declared the winner of Ecuador's closely contested presidential election.