如何用Browserify实现Smartsheet API客户端代码?报错求助
问题:Browserify构建Smartsheet API客户端后执行报错TypeError: Cannot read property 'write' of undefined
问题背景
在Web应用中通过HTML页面实现用户反馈提交后更新Smartsheet表格,使用Browserify构建Smartsheet API客户端代码时,执行函数触发如下错误:
bundle.js:58387 Uncaught (in promise) TypeError: Cannot read property 'write' of undefined at exports.Console.Console.log (bundle.js:58387) at transportLog (bundle.js:57729) at bundle.js:42474 at eachOfArrayLike (bundle.js:40433) at eachOf (bundle.js:40481) at Object.eachLimit (bundle.js:42536) at exports.Logger.Logger.log (bundle.js:57741) at logRequestBasics (bundle.js:53943) at Object.logRequest (bundle.js:53910) at methodRequest (bundle.js:53836) at Object.get (bundle.js:53793) at Object.listSheets (bundle.js:52964) at updateSmartsheet (Dummy.js:160)
操作步骤回顾
- 安装依赖:
npm install smartsheet browserify
- 创建
main.js:
const client = require('smartsheet'); const smartsheet = client.createClient({ accessToken: 'secret token', logLevel: 'info' }); global.window.smartsheet = smartsheet;
- 执行打包命令:
browserify main.js -o bundle.js
- HTML中引入打包文件:
<script src="./lib/bundle.js"></script>
- 编写并调用
updateSmartsheet函数:
function updateSmartsheet(){ const smartsheet = window.smartsheet; var options = { queryParameters: { include: "attachments", includeAll: true } }; smartsheet.sheets.listSheets(options) .then(function (result) { var sheetId = result.data[0].id; smartsheet.sheets.getSheet({id: sheetId}) .then(function(sheetInfo) { console.log(sheetInfo); }) .catch(function(error) { console.log(error); }); }) .catch(function(error) { console.log(error); }); }
报错原因
错误根源是Smartsheet SDK的日志模块默认依赖Node.js环境的console._stdout.write方法,但浏览器环境中没有这个属性,导致调用日志输出时触发TypeError。
解决方案
方案1:关闭日志输出(最简单)
修改main.js中客户端创建代码,将logLevel设为silent,彻底禁用日志输出:
const smartsheet = client.createClient({ accessToken: 'secret token', logLevel: 'silent' // 替换原有的'info' });
方案2:自定义日志传输器(保留日志功能)
如果需要保留日志输出,可自定义适配浏览器的日志处理逻辑:
const client = require('smartsheet'); const smartsheet = client.createClient({ accessToken: 'secret token', logLevel: 'info', // 自定义logger,用浏览器原生console输出日志 logger: { log: function(level, message) { if (typeof console[level] === 'function') { console[level](message); } else { console.log(`[${level}] ${message}`); } } } }); global.window.smartsheet = smartsheet;
方案3:替换Browserify的console模块(进阶)
安装浏览器兼容的console模块,并在打包时替换Node.js原生console:
- 安装依赖:
npm install console-browserify --save-dev
- 执行打包命令:
browserify main.js -r console-browserify:console -o bundle.js
内容的提问来源于stack exchange,提问作者Laxmikant sahu
相关产品推荐
相关产品推荐

