Using Dayjs in your application as plugins
On this page
#What's an plugin is ?
A plugin is an independent module that can be added to Day.js to extend functionality or add new features (from dayjs docs). We can add and group our custom date related functionalities as plugins.
#Let's write an dayjs plugin which will convert an date to human readable time string without seconds. (This is the sandbox)
This sandbox have folder dayjs-plugins, which contains formatTimestampPlugin.ts file.
#dayjs-plugins folder in the sandbox :
It contains the date related plugins and group them file wise. We have added an
formatTimestampPluginfile which will contain all the date realted methods which will format the time as per our requirement.In
formatTimestampPlugin.tsfile we have defined ourformatAsReadableTimeWithoutSecondsmethod, which formats the a given timestamp to readable string with hours and minutes of an timestamp.We have exposed our plugins via index.ts file of
dayjs-pluginsfolder.We have imported all our plugins at very load of the app i.e. inside the main.ts file. Because we have loaded our plugins at the top, now we can use it anywhere inside our app.
#Usage and benefits using custom app related methods/functionalities as plugins:
We can group the related methods/functionalities inside a plugin.
Once we extend the plugin and import it at the time of app load, we can use it anywhere inside our app.
We can access our methods directly on the dayjs objects, which helps in write more readable code and auto suggestion while accessing these methods on dayjs objects.
#App structure(sandbox):
dayjs-pluginsfolder
dayjs-pluginsfolder haveformatTimestampPlugin.tsfile which will contain date related functionalities for formatting the dayjs timestamp to readable string.It have
index.tsfile which imports all the plugin files and extend them withdayjs.extend(myPlaugin)method.
main.tsfile
Here we have imported the
dayjs-plugins/index.tsat the very top of the file so that we have all our plugins available to be used once our app gets loaded.Once our plugins gets loaded we have all our methods available to be used in our application.