使用Browserify打包@google/earthengine后MDOutSystems未定义问题求助
解决Browserify打包Google Earth Engine API后MDOutSystems未定义的问题
问题排查与修复步骤
1. 修正main.js中的原型链错误
你的main.js里MDOutSystems.prototype.data.authenticateViaPrivateKey存在逻辑问题:MDOutSystems.prototype.data未初始化就直接添加方法,会触发运行时错误,进而影响模块正常导出。先修改代码:
var md = require('@google/earthengine'); module.exports = MDOutSystems; function MDOutSystems() { this.mdInstance = md; }; // 先初始化原型上的data对象,再挂载方法 MDOutSystems.prototype.data = {}; MDOutSystems.prototype.data.authenticateViaPrivateKey = function( privateKey, opt_success, opt_error, opt_extraScopes, opt_suppressDefaultScopes) { md.data.authenticateViaPrivateKey(privateKey, opt_success, opt_error, opt_extraScopes, opt_suppressDefaultScopes); }; MDOutSystems.prototype.initialize = function() { md.initialize(); }; // 建议返回Image实例,否则调用后无法获取对象 MDOutSystems.prototype.Image = function(source) { return md.Image(source); }; MDOutSystems.prototype.getInstance = function () { return this.mdInstance; }
2. 确保Browserify命令正确执行
- 若未全局安装Browserify,先执行:
npm install -g browserify - 切换到main.js所在目录,执行打包命令(注意命令为小写
browserify):browserify main.js --standalone MDOutSystems > google-earth-outsystems.js - 若使用局部安装的Browserify,用npx调用:
npx browserify main.js --standalone MDOutSystems > google-earth-outsystems.js
3. 正确加载打包文件
在浏览器环境中,确保脚本加载完成后再调用MDOutSystems:
<script src="./google-earth-outsystems.js"></script> <script> // 等待脚本加载完成后执行 var ee = new MDOutSystems(); ee.initialize(); </script>
若在Node.js环境使用,直接通过require('./google-earth-outsystems.js')导入即可。
4. 验证打包结果
打开生成的google-earth-outsystems.js,搜索MDOutSystems,确认它被挂载到全局对象(浏览器中为window.MDOutSystems)。如果未找到,重新执行打包命令,检查是否有报错信息。
5. 消除TypeScript警告(可选)
针对需要创建d.ts文件的警告,在项目根目录新建google-earthengine.d.ts文件,内容如下:
declare module '@google/earthengine' { export const data: { authenticateViaPrivateKey: ( privateKey: any, opt_success?: () => void, opt_error?: (err: Error) => void, opt_extraScopes?: string[], opt_suppressDefaultScopes?: boolean ) => void; }; export function initialize(): void; export function Image(source: any): any; }
内容的提问来源于stack exchange,提问作者anon
相关产品推荐
相关产品推荐

