简体   繁体   English

Ojbc调用js错误:找不到变量require

[英]Ojbc invoke js error: Can't find variable require

I'm totally new to JS. 我是JS的新手。 I'm developing on ios and we need to use Web3js in our program. 我在ios上进行开发,我们需要在程序中使用Web3js。 It's ok to call js function in obj-c. 可以在obj-c中调用js函数。 However, I use 'require' to import Web3js modules, it throws 'ReferenceError: Can't find variable: require'. 但是,我使用'require'导入Web3js模块,它引发'ReferenceError:找不到变量:require'。 What happens? 怎么了? Did I miss anything? 我有想念吗? Anyone can help?? 任何人都可以帮忙吗? Many thanks. 非常感谢。

update: 更新:

If 'require' is not usable, how could I use other modules from js invoked by obj-c? 如果'require'不可用,如何使用obj-c调用的js中的其他模块?

here is my code. 这是我的代码。

obj-c code: obj-c代码:

NSString* path = [[NSBundle mainBundle] pathForResource:@"bridge/src/index" ofType:@"js"];
jsFunc = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];

JSContext* jsContext = [[JSContext alloc] init];
[jsContext evaluateScript:jsFunc];
JSValue* func = jsContext[@"getAddress"];
JSValue* = [func2 callWithArguments:@[@"0x8730f6ad1c0d387644590966bdbfedba44fe250118df0f97f11190ad5727b312"]];    

js: js:

function getAddress(prvKey)
{
  try{
      var Web3 = require('../../3rd_party/web3.js-1.0.0');     
      var web3 = new Web3();
      return web3.eth.accounts.privateKeyToAccount(prvKey);
  }
  catch (e)
  {
      return e;
  }
}

I used Browserify to package all modules and then used webView to call the js functions. 我使用Browserify打包所有模块,然后使用webView调用js函数。

here is my js file, index.js 这是我的js文件index.js

"use strict"
let Web3 = require('web3.js');
window.Web3 = Web3;

and then use Broswerify to pack 然后使用Broswerify打包

browserify index.js -o web3.js

my html, 我的html

<html>
<head>
    <script type="text/javascript" src="web3.js"></script>   
</head>
<body>
    <script type="text/javascript">
        function getAddress(prvkey)
        {
            try
            {
                var web3 = new Web3();
                var account  = web3.eth.accounts.privateKeyToAccount(prvkey);
                return account.address;
            }
            catch (e)
            {
                return e;
            }
        }
    </script>
</body>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM