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

Clasp编译生成代码导入失效,如何解决Clasp项目导入问题?

如何让Clasp项目中的TypeScript导入功能正常工作?

我的TypeScript源文件

src/main.ts

function main(): void {
    console.log('main');
    hello(); 
}

src/other.ts

console.log('hello world');
}

编译生成的Google Apps脚本文件

src/main.gs

var module = module || { exports: exports };
//import {hello} from "./other";
function main() {
    console.log('main');
    (0, other_1.hello)();
}

src/other.gs

var exports = exports || {};
var module = module || { exports: exports };
exports.hello = void 0;
function hello() {
    console.log('hello world');
}
exports.hello = hello;

运行错误

执行main()函数时触发ReferenceError: other_1 is not defined错误。

解决方法

Clasp搭配TypeScript时,默认模块编译逻辑不兼容Google Apps Script的全局执行环境,需按以下步骤调整:

  1. 修正TypeScript模块语法
    先补全并标准化src/other.ts的导出代码:

    export function hello() {
        console.log('hello world');
    }
    

    在src/main.ts中添加正确的导入语句:

    import { hello } from './other';
    
    function main(): void {
        console.log('main');
        hello(); 
    }
    
  2. 修改tsconfig.json编译配置
    Google Apps Script不支持CommonJS模块规范,需配置TypeScript将所有文件合并为单个GS文件,确保全局环境能识别所有函数。调整后的tsconfig.json示例:

    {
      "compilerOptions": {
        "target": "ES3",
        "module": "ESNext",
        "lib": ["ESNext"],
        "outFile": "src/Code.gs",
        "strict": true,
        "esModuleInterop": true,
        "skipLibCheck": true,
        "forceConsistentCasingInFileNames": true,
        "moduleResolution": "Node",
        "allowJs": true
      },
      "include": ["src/**/*"],
      "exclude": ["node_modules", ".clasp.json"]
    }
    

    核心是"outFile"配置,它会将所有编译后的代码合并到指定文件中,避免模块变量未定义的问题。

  3. 重新编译并推送项目
    执行tsc编译代码,再用clasp push将合并后的Code.gs推送到Google Apps Script项目,此时运行main()就能正常调用hello()函数。

如果不想合并单文件,也可以手动将函数挂载到全局对象:在other.gs末尾添加globalThis.hello = hello;,然后在main.gs中直接调用hello(),但这种方式在复杂项目中容易引发命名冲突,推荐使用单文件合并方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 21:43:32