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的全局执行环境,需按以下步骤调整:
修正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(); }修改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"配置,它会将所有编译后的代码合并到指定文件中,避免模块变量未定义的问题。重新编译并推送项目
执行tsc编译代码,再用clasp push将合并后的Code.gs推送到Google Apps Script项目,此时运行main()就能正常调用hello()函数。
如果不想合并单文件,也可以手动将函数挂载到全局对象:在other.gs末尾添加globalThis.hello = hello;,然后在main.gs中直接调用hello(),但这种方式在复杂项目中容易引发命名冲突,推荐使用单文件合并方案。
内容的提问来源于stack exchange,提问作者sheamus
相关产品推荐
相关产品推荐

