I want to do the following day.js configuration:
import dayjs from 'dayjs';
// add plugins for timezone functionality
import utc from 'dayjs/plugin/utc';
import timezone from 'dayjs/plugin/timezone';
dayjs.extend(utc);
dayjs.extend(timezone);
// set default timezone
dayjs.tz.setDefault("America/New_York");
// set default format (source: https://stackoverflow.com/a/77459776/22134371)
dayjs.extend((option, dayjsClass, dayjsFactory) => {
const oldFormat = dayjsClass.prototype.format;
dayjsClass.prototype.format = function (formatString) {
return oldFormat.bind(this)(formatString ?? 'YYYY-MM-DD')
}
});
How do I define this only once in my React project, so that in every file that I use dayjs, it includes these configurations (timezone plugins, default timezone, and overriden format method)?
Thanks for any help!
2
Answers
You can just import it on the file that renders your app.
You can create a new file in your project where you will set up and export the configured dayjs. Then name this file something like configuredDayjs.js (or .ts if you’re using TypeScript).
configuredDayjs.js:
Whenever you need to use dayjs in your project, import it from your custom module instead of directly from the dayjs package.
For example, in a React component: