I was setting up the blog page for a website and needed to format the article’s date
and updatedAt
fields. I used this logic to determine whether to display the published or updated date:
{
blog.updatedAt === blog.date
? `Published on ${format(new Date(blog.date), "MMM dd, yyyy")}`
: `Updated on ${format(new Date(blog.updatedAt), "MMM dd, yyyy")}`;
}
However, I noticed a squiggly line under the import
statement for format
. I had written:
import format from "date-fns";
When I hovered over the error, it said:Module '".../node_modules/date-fns/index"' has no default export.ts(1192)
I realized the issue was because date-fns
doesn’t have a default export. Each function, including format
, needs to be imported as a named export.
I followed these steps to fix the issue:
Checked the import
Statement
I updated the import
statement to:
import { format } from "date-fns";
Tested the Code
After updating the import, the error disappeared, and the formatting worked as expected.
Verified the Output
The dates were displayed correctly on the blog page, formatted as "MMM dd, yyyy"
.
Here’s the corrected code:
import { format } from "date-fns";
{
blog.updatedAt === blog.date
? `Published on ${format(new Date(blog.date), "MMM dd, yyyy")}`
: `Updated on ${format(new Date(blog.updatedAt), "MMM dd, yyyy")}`;
}
By importing format
as a named export, I resolved the error and successfully formatted the dates.