ANNANDALE, Va. — Propelled by demographic changes that are turning Virginia into an increasingly blue state and a liberal base energized by the convulsive Trump presidency, Democrats have long been favored to retain the governorship here when the state goes to the polls on Tuesday.

But a racially tinged, divisive campaign by the Republican nominee, Ed Gillespie, who has transformed himself from establishment fixture to culture warrior, has tightened the race and, perhaps, presented a template for how to run a state campaign in the Trump era.

And while he is still favored to win, Lt. Gov. Ralph S. Northam, the Democratic candidate, is under duress from both his Republican opponent and his own left flank in ways that could foreshadow his party’s challenges in next year’s midterm races.

For all the talk of Republican divisions, the party of President Trump has largely rallied around Mr. Gillespie’s confrontational candidacy in what is probably the most consequential election since Mr. Trump took office. While Mr. Gillespie kept the president out of Virginia, the only Southern state Mr. Trump lost, he has run a campaign that gave Mr. Trump much to admire.