在Google Apps Script中替换Moment.js为Luxon时出现错误
解决方案:Google Apps Script中替换Moment.js为Luxon
问题核心是Luxon与Moment.js的全局暴露机制不同:
- Moment.js直接将核心函数
moment挂载到全局作用域 - Luxon则将所有核心类封装在全局
Luxon对象中,无法直接访问DateTime、Duration等类
修正方法
1. 通过CDN加载时的修正
保留你的加载代码,调用Luxon类时通过Luxon全局对象访问:
// 加载Luxon库 eval(UrlFetchApp.fetch('https://cdn.jsdelivr.net/npm/luxon@3.0.3/build/global/luxon.min.js').getContentText()); // 直接调用示例 console.log(Luxon.DateTime.now().toString()); // (可选)简化引用,后续可直接用DateTime const DateTime = Luxon.DateTime; console.log(DateTime.now().toString());
2. 复制Luxon代码到luxon.gs时的修正
将luxon.min.js内容复制到luxon.gs后,同样需要通过Luxon对象访问核心类,或提前赋值简化:
// 从luxon.gs的全局对象中提取类 const { DateTime, Duration, Interval } = Luxon; // 调用示例 console.log(DateTime.now().toString());
验证说明
执行上述代码后,即可正常输出当前时间的字符串格式,不会再抛出ReferenceError: DateTime is not defined错误。
内容的提问来源于stack exchange,提问作者Ian Hyzy
相关产品推荐
相关产品推荐

