Falak
WebDevelopment

Using Dayjs in your application as plugins

1 min read

#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 formatTimestampPlugin file which will contain all the date realted methods which will format the time as per our requirement.

  • In formatTimestampPlugin.ts file we have defined our formatAsReadableTimeWithoutSeconds method, 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-plugins folder.

  • 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.

  • 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-plugins folder

  1. dayjs-plugins folder have formatTimestampPlugin.ts file which will contain date related functionalities for formatting the dayjs timestamp to readable string.

  2. It have index.ts file which imports all the plugin files and extend them with dayjs.extend(myPlaugin) method.

  • main.ts file

  1. Here we have imported the dayjs-plugins/index.ts at the very top of the file so that we have all our plugins available to be used once our app gets loaded.

  2. Once our plugins gets loaded we have all our methods available to be used in our application.

Share this post