“I will say what I have said already before: We are for solidarity, but we are against stupidity,” he said, advocating a policy of discouraging migrants from coming to Europe by improving conditions in their own countries.

Since the nation’s independence from Communist Yugoslavia in 1991, politics in Slovenia has had a conservative tinge, but center and leftist parties have largely dominated governing coalitions. The shift to populist parties has taken place since the migration crisis of 2015 and 2016, though the shift has not been as strong as in neighboring Italy, where an anti-establishment government was sworn in last week.

The centrist party of Marjan Sarec, a former actor and the mayor of Kamnik, a small town north of the capital, Ljubljana, came in second with 13 percent of the vote. Mr. Sarec, 40, came close to unseating the incumbent, Borut Pahor, in the presidential election last year.

Mr. Sarec cast himself as an anti-establishment candidate and a leader for a new generation of Slovenians who have come of age in a democratic society and whose top concerns are the economy, jobs and social security, including a robust pension system.

He congratulated Mr. Jansa for the victory on Sunday, but said his party would heed its vow not to form a coalition with the populist party. If Mr. Jansa fails to cobble together a government, Mr. Sarec would get a chance. If he too failed, the president could call new elections.

Finishing third in the poll were the Social Democrats of Dejan Zidan, with 10 percent.

The Modern Center Party, led by the outgoing prime minister, Miro Cerar, finished fourth with 9.5 percent — a crushing defeat considering that Slovenia’s economy grew by 5 percent on his government’s watch in 2017, one of the fastest rates on the continent, according to the European Union.

The election for the 90-seat legislature took place a few weeks earlier than the normal four years because of Mr. Cerar’s abrupt resignation in March after a major infrastructure project he had backed was shelved.