never meant

'Cause you can't miss what you forget

【GAS】GASライブラリを使わず、CDNから取得して使う方法

モチベーション

GASでDay.jsを使いたくなったけど、非公式なライブラリを使うことに違和感を感じたので調べた。

コード

function useDayjs() {
  const cacheExpire = 3600
  const dayjsCache = 'dayjsCache'

  let cache = CacheService.getUserCache()
  let cachedData = cache.get(dayjsCache)

  if (cachedData) {
    eval(cachedData)
  } else {
    var response = UrlFetchApp.fetch(
      'https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.10.7/dayjs.min.js'
    ).getContentText()
    cache.put(dayjsCache, response, cacheExpire)
    eval(response)
  }
}

// 呼び出し、実行例
useDayjs()
dayjs().subtract(15, 'minute').format()

参考元

stackoverflow.com developers.google.com GASにキャッシュサービスがあるなんて知らなかった