Search code examples
javascriptobjective-cweb3js

Ojbc invoke js error: Can't find variable require


I'm totally new to JS. I'm developing on ios and we need to use Web3js in our program. It's ok to call js function in obj-c. However, I use 'require' to import Web3js modules, it throws 'ReferenceError: Can't find variable: 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?

here is my code.

obj-c code:

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:

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;
  }
}

Solution

  • I used Browserify to package all modules and then used webView to call the js functions.

    here is my js file, index.js

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

    and then use Broswerify to pack

    browserify index.js -o web3.js
    

    my 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>