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

Google App Script库部署至Google Sheet方法及调用报错问题求助

如何将Google App Script Library部署到Google Sheet

一、创建并部署库脚本

  • 打开Google Apps Script平台,新建脚本并命名(比如你的MySimpleSharedCode)
  • 编写库代码后,点击右上角部署 > 新部署
  • 部署类型选择库,填写版本说明,设置访问权限(测试阶段可选择「任何人,甚至匿名」),点击部署
  • 部署完成后复制库的脚本ID,后续引用会用到

二、在Google Sheet中关联库

  • 打开目标Google Sheet,点击扩展程序 > Apps Script进入关联脚本编辑器
  • 点击左侧库图标(📚),选择添加库
  • 粘贴复制的脚本ID,点击查找,选择要使用的库版本,设置标识符(保持默认MySimpleSharedCode即可),点击添加
  • 完成后即可在Sheet的脚本中调用库功能

解决调用报错:TypeError: MySimpleSharedCode.sayHello is not a function

你的问题核心是库的代码暴露方式不符合Google Apps Script的规则——库只会暴露顶层函数,你定义的MySimpleSharedCode.sayHello是对象内部方法,无法被外部脚本识别。

修正方案

方案1:改为顶层函数(最简方式)

修改MySimpleSharedCode的代码,把需要暴露的函数直接放在顶层:

function sayHello() {
  return "hello from MySimpleSharedCode";
}

function sayHello2() {
  var result = sayHello();
  console.log(result);
  return result;
}

重新部署库(创建新版本),然后在BorrowerCode中调用:

function sayHello3() {
  var result = MySimpleSharedCode.sayHello();
  console.log(result);
  return result;
}

方案2:使用export暴露对象(适合多方法组织)

如果要保留对象结构,可借助V8运行时的export语法(默认已启用):
修改MySimpleSharedCode的代码:

const MySimpleSharedCode = {
  sayHello: function() {
    return "hello from MySimpleSharedCode";
  }
};

export { MySimpleSharedCode };

function sayHello2() {
  var result = MySimpleSharedCode.sayHello();
  console.log(result);
  return result;
}

在BorrowerCode中通过import引入:

import { MySimpleSharedCode } from 'MySimpleSharedCode';

function sayHello3() {
  var result = MySimpleSharedCode.sayHello();
  console.log(result);
  return result;
}

注意:修改库代码后必须创建新部署版本,并在调用脚本的库设置中切换到新版本,否则会继续调用旧代码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 02:52:51