You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Webpack打包的Dayjs模块在Google AppScript中无法使用

问题:Google Apps Script中引入打包后的Dayjs提示未定义

我尝试用Google Apps Script开发自动化脚本,引入npm的Dayjs模块并通过Webpack打包适配GAS,但脚本无法运行,AppScript提示Dayjs未定义,怀疑是Webpack打包/压缩环节出了问题。相关代码及报错信息如下:

Code.gs代码

const testDayjs = () => console.log (
    dayjs()
    .startOf('month')
    .add(1, 'day')
    .set('year', 2022)
    .format('YYYY-MM-DD HH:mm:ss')
);
console.log ('finished', Dayjs)

Day.gs代码(Webpack打包后)

var Dayjs;(()=>{var t={484:function(t){t.exports=function(){"use strict";var t=6e4,e=36e5,n="millisecond",r="second",i="minute",s="hour",u="day",a="week",o="month",f="quarter",h="year",c="date",d="Invalid Date",l=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,$=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,y={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_")},v=function(t,e,n){var r=String(t);return!r||r.length>=e?t:""+Array(e+1-r.length).join(n)+t},M={s:v,z:function(t){var e=-t.utcOffset(),n=Math.abs(e),r=Math.floor(n/60),i=n%60;return(e<=0?"+":"-")+v(r,2,"0")+":"+v(i,2,"0")},m:function t(e,n){if(e.date()<n.date())return-t(n,e);var r=12*(n.year()-e.year())+(n.month()-e.month()),i=e.clone().add(r,o),s=n-i<0,u=e.clone().add(r+(s?-1:1),o);return+(-(r+(n-i)/(s?i-u:u-i))||0)},a:function(t){return t<0?Math.ceil(t)||0:Math.floor(t)},p:function(t){return{M:o,y:h,w:a,d:u,D:c,h:s,m:i,s:r,ms:n,Q:f}[t]||String(t||"").toLowerCase().replace(/s$/,'')},u:function(t){return void 0===t}},m="en",g={};g[m]=y;var p=function(t){return t instanceof O},D=function t(e,n,r){var i;if(!e)return m;if("string"==typeof e){var s=e.toLowerCase();g[s]&&(i=s),n&&(g[s]=n,i=s);var u=e.split("-");if(!i&&u.length>1)return t(u[0])}else{var a=e.name;g[a]=e,i=a}return!r&&i&&(m=i),i||!r&&m},S=function(t,e){if(p(t))return t.clone();var n="object"==typeof e?e:{};return n.date=t,n.args=arguments,new O(n)},w=M;w.l=D,w.i=p,w.w=function(t,e){return S(t,{locale:e.$L,utc:e.$u,x:e.$x,$offset:e.$offset})};var O=function(){function y(t){this.$L=D(t.locale,null,!0),this.parse(t)}var v=y.prototype;return v.parse=function(t){this.$d=function(t){var e=t.date,n=t.utc;if(null===e)return new Date(NaN);if(w.u(e))return new Date;if(e instanceof Date)return new Date(e);if("string"==typeof e&&!/Z$/i.test(e)){var r=e.match(l);if(r){var i=r[2]-1||0,s=(r[7]||"0").substring(0,3);return n?new Date(Date.UTC(r[1],i,r[3]||1,r[4]||0,r[5]||0,r[6]||0,s)):new Date(r[1],i,r[3]||1,r[4]||0,r[5]||0,r[6]||0,s)}}return new Date(e)}(t),this.$x=t.x||{},this.init()},v.init=function(){var t=this.$d;this.$y=t.getFullYear(),this.$M=t.getMonth(),this.$D=t.getDate(),this.$W=t.getDay(),this.$H=t.getHours(),this.$m=t.getMinutes(),this.$s=t.getSeconds(),this.$ms=t.getMilliseconds()},v.$utils=function(){return w},v.isValid=function(){return!(this.$d.toString()===d)},v.isSame=function(t,e){var n=S(t);return this.startOf(e)<=n&&n<=this.endOf(e)},v.isAfter=function(t,e){return S(t)<this.startOf(e)},v.isBefore=function(t,e){return this.endOf(e)<S(t)},v.$g=function(t,e,n){return w.u(t)?this[e]:this.set(n,t)},v.unix=function(){return Math.floor(this.valueOf()/1e3)},v.valueOf=function(){return this.$d.getTime()},v.startOf=function(t,e){var n=this,f=!!w.u(e)||e,d=w.p(t),l=function(t,e){var r=w.w(n.$u?Date.UTC(n.$y,e,t):new Date(n.$y,e,t),n);return f?r:r.endOf(u)},$=function(t,e){return w.w(n.toDate()[t].apply(n.toDate("s"),(f?[0,0,0,0]:[23,59,59,999]).slice(e)),n)},y=this.$W,v=this.$M,M=this.$D,m="set"+(this.$u?"UTC":""),g=this.$locale().weekStart||0,p=(y<g?y+7:y)-g;switch(d){case h:return f?l(1,0):l(31,11);case o:return f?l(1,v):l(0,v+1);case a:return l(f?M-p:M+(6-p),v);case u:case c:return $(m+"Hours",0);case s:return $(m+"Minutes",1);case i:return $(m+"Seconds",2);case r:return $(m+"Milliseconds",3);default:return this.clone()}},v.endOf=function(t){return this.startOf(t,!1)},v.$set=function(t,e){var a,f=w.p(t),d="set"+(this.$u?"UTC":""),l=(a={},a[u]=d+"Date",a[c]=d+"Date",a[o]=d+"Month",a[h]=d+"FullYear",a[s]=d+"Hours",a[i]=d+"Minutes",a[r]=d+"Seconds",a[n]=d+"Milliseconds",a)[f],$=f===u?this.$D+(e-this.$W):e;if(f===o||f===h){var y=this.clone().set(c,1);y.$d[l]($),y.init(),this.$d=y.set(c,Math.min(this.$D,y.daysInMonth())).$d}else l&&this.$d[l]($);return this.init(),this},v.set=function(t,e){return this.clone().$set(t,e)},v.get=function(t){return this[w.p(t)]()},v.add=function(n,f){var c,d=this;n=Number(n);var l=w.p(f),$=function(t){var e=S(d);return w.w(e.date(e.date()+Math.round(t*n)),d)};if(l===o)return this.set(o,this.$M+n);if(l===h)return this.set(h,this.$y+n);if(l===u)return $(1);if(l===a)return $(7);var y=(c={},c[i]=t,c[s]=e,c[r]=1e3,c)[l]||1,v=this.$d.getTime()+n*y;return w.w(v,this)},v.subtract=function(t,e){return this.add(-1*t,e)},v.format=function(t){var e=this,n=this.$locale();if(!this.isValid())return n.invalidDate||d;var r=t||"YYYY-MM-DDTHH:mm:ssZ",i=w.z(this),s=this.$H,u=this.$m,a=this.$M,o=n.weekdays,f=n.months,h=function(t,n,i,s){return t&&(t[n]||t(e,r))||i[n].slice(0,s)},c=function(t){return w.s(s%12||12,t,"0")},l=n.meridiem||function(t,e,n){var r=t<12?"AM":"PM";return n?r.toLowerCase():r},y={YY:String(this.$y).slice(-2),YYYY:this.$y,M:a+1,MM:w.s(a+1,2,"0"),MMM:h(n.monthsShort,a,f,3),MMMM:h(f,a),D:this.$D,DD:w.s(this.$D,2,"0"),d:String(this.$W),dd:h(n.weekdaysMin,this.$W,o,2),ddd:h(n.weekdaysShort,this.$W,o,3),dddd:o[this.$W],H:String(s),HH:w.s(s,2,"0"),h:c(1),hh:c(2),a:l(s,u,!0),A:l(s,u,!1),m:String(u),mm:w.s(u,2,"0"),s:String(this.$s),ss:w.s(this.$s,2,"0"),SSS:w.s(this.$ms,3,"0"),Z:i};return r.replace($,(function(t,e){return e||y[t]||i.replace(":","")}))},v.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},v.diff=function(n,c,d){var l,$=w.p(c),y=S(n),v=(y.utcOffset()-this.utcOffset())*t,M=this-y,m=w.m(this,y);return m=(l={},l[h]=m/12,l[o]=m,l[f]=m/3,l[a]=(M-v)/6048e5,l[u]=(M-v)/864e5,l[s]=M/e,l[i]=M/t,l[r]=M/1e3,l)[$]||M,d?m:w.a(m)},v.daysInMonth=function(){return this.endOf(o).$D},v.$locale=function(){return g[this.$L]},v.locale=function(t,e){if(!t)return this.$L;var n=this.clone(),r=D(t,e,!0);return r&&(n.$L=r),n},v.clone=function(){return w.w(this.$d,this)},v.toDate=function(){return new Date(this.valueOf())},v.toJSON=function(){return this.isValid()?this.toISOString():null},v.toISOString=function(){return this.$d.toISOString()},v.toString=function(){return this.$d.toUTCString()},y}(),_=O.prototype;return S.prototype=_,[["$ms",n],["$s",r],["$m",i],["$H",s],["$W",u],["$M",o],["$y",h],["$D",c]].forEach((function(t){_[t[1]]=function(e){return this.$g(e,t[0],t[1])}})),S.extend=function(t,e){return t.$i||(t(e,O,S),t.$i=!0),S},S.locale=D,S.isDayjs=p,S.unix=function(t){return S(1e3*t)},S.en=g[m],S.Ls=g,S.p={},S}()}},e={};function n(r){var i=e[r];if(void 0!==i)return i.exports;var s=e[r]={exports:{}};return t[r].call(s.exports,s,s.exports,n),s.exports}n.d=(t,e)=>{for(var r in e)n.o(e,r)&&!n.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:e[r]})},n.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),n.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})};var r={};(()=>{"use strict";n.r(r),n.d(r,{dayjs:()=>t});const t=n(484)})(),Dayjs=r})();

报错信息

Error
TypeError: Cannot destructure property 'dayjs' of 'Dayjs' as it is undefined.
(anonymous)
@ 

解决方案

问题根源

Webpack打包后的代码将Dayjs封装成了ES模块格式,而Google Apps Script的运行环境不支持ES模块的解构语法,且全局变量赋值逻辑有误:打包后的代码把模块对象赋值给了Dayjs变量,但实际的Dayjs构造函数是模块对象里的dayjs属性,而你在Code.gs里直接调用dayjs(),该变量并未在全局作用域定义。

修复方案1:修改Webpack配置,直接暴露全局变量

调整webpack.config.js的输出配置,让Webpack把Dayjs直接挂载到全局作用域:

module.exports = {
  // 其他配置(入口、loader等)保持不变
  output: {
    filename: 'Day.gs',
    library: 'dayjs', // 将dayjs作为全局变量名暴露
    libraryTarget: 'window' // 挂载到全局window对象(GAS环境中window等同于全局this)
  }
};

重新执行打包后,Day.gs会直接在全局作用域定义dayjs变量,Code.gs里的testDayjs函数就能正常调用。

修复方案2:手动修改打包后的Day.gs代码

如果不想重新打包,可以直接修改Day.gs的最后一行:

  • 原代码最后一行:Dayjs=r})();
  • 修改为:dayjs=r.dayjs;})();
    修改后,全局作用域就会出现dayjs变量,同时把Code.gs里的console.log ('finished', Dayjs)改成console.log ('finished', dayjs)即可。

额外注意:脚本加载顺序

在Google Apps Script编辑器中,确保Day.gs文件在Code.gs文件上方(可以通过拖动文件调整顺序),这样全局变量dayjs会先被定义,再被Code.gs里的代码调用。


内容的提问来源于stack exchange,提问作者Vagabundo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 09:24:25