Nuxt.jsの日付処理系プラグインをmoment.jsからday.jsに移行する

  • 公開日アイコン
  • 更新日アイコン
Nuxt.jsの日付処理系プラグインをmoment.jsからday.jsに移行する メイン画像

Ad Area

ブラックフライデーセール. 最大 90%OFF

時刻表記するのに便利なJavaScriptプラグイン「Moment.js」のプロジェクト終了が決まっていたらしい。そうとは知らず当ブログのNuxt.jsプロジェクトで取り入れていたので、別のプラグイン「Day.js」に移行することにした。

moment.js

日付処理系ライブラリの決定版「Moment.js」を使ってNuxt.jsでの日付操作を楽にしよう | PAPADAYS.COM」を参考に行ったmoment.jsの設定は以下の通り。

plugin/moment.js
import Vue from 'vue'
import moment from 'moment'

// YYYY年MM月DD日形式で表示するようfilterを定義
Vue.filter('format-date', function (value) {
  const date = moment(value);
  return date.format("YYYY年MM月DD日");
})
nuxt.config.js
// グローバルでpluginを使えるようにする
plugins: [
    {src: '~/plugins/day'},
],

// モジュールを登録
modules: [
  '@nuxtjs/moment',
],

// 日本語化
moment: {
  locales: ['ja']
},

vueファイル内の表示したい箇所に記述

<time>{{ new Date() | format-date }}</time>

これをday.jsの仕様に変更していく。

moment.jsをday.jsに変更

moment.jsのアンインストールとday.jsのインストール

npm install @nuxtjs/moment

npm install dayjs

pluginフォルダ内にday.jsを作成する。moment.jsと異なるのは、日本語化設定はnuxt.config.jsではなくday.js内で行う点である。

※2022年5月5日追記 Vue3系でfilter非推奨になる予定なので、先々の対応のためにfilterを使わない記法に変更

day.js
// 日本語化できるようインポート
import 'dayjs/locale/ja'
import Vue from 'vue'
import dayjs from 'dayjs'

// 日本語化設定
dayjs.locale('ja')

// Vue3系でfilter非推奨のため、以下に変更
Vue.prototoye.$dayjs = dayjs
nuxt.config.js
// グローバルでpluginを使えるようにする
plugins: [
  {src: '~/plugins/day'},
],

vueファイル内の記法はmoment.jsと同じなので、変更する必要はない。

CardList.vue
<li class="c-meta c-meta--published mr-2">
  <svg class="c-icon-xs align-text-bottom inline-block"><title>公開日アイコン</title><desc></desc><use xlink:href="#published"/></svg><time :datetime="post.published">{{ post.published | date-format }}</time>
</li>
CardList.vue
<li class="c-meta c-meta--published mr-2">
  <svg class="c-icon-xs align-text-bottom inline-block"><title>公開日アイコン</title><desc></desc><use xlink:href="#published"/></svg><time :datetime="$dayjs(post.published).format('YYYY-MM-DD')">{{ $dayjs(post.published).format('YYYY年MM月DD日') }}</time>
</li>

参考ページ

Ad Area