Dynamic require not supported in React Native - node.js

I have just tried to use wasm bindings in a react-native project. But the wasm bindings require access to node modules like fs so I used rn-nodeify as a work-around to get the React Native representation of fs and to be able to use require. That worked fine but I think that the wasm bindings are incompatible with react native, because I get the error Dynamic require defined at line 10; not supported by Metro. The error is talking about the line below:
//line 10
const { TextDecoder, TextEncoder, inspect } = require(String.raw`util`);
The bindings I'm using are from this package #iota/identity-wasm
Steps to reproduce
If you want to reproduce this issue I have created a sample RN Project that throws the error by startup.
git clone https://github.com/JonasHiltl/DigitalIdentityNodeified.git
cd ./DigitalIdentityNodeified
npm install
npx react-native start
npx react-native run-android
I'm interested to know what exactly a dynamic require is and if it's possible to replace the dynamic require with a normal one.

Sadly you cannot use require dynamicly in react-native :/
You will have to make a require for every single thing you will need.
Check out this for example:
Dynamic require not supported in React Native

Related

If an npm package ships with multiple dist folders, how do I know which one is used when my App is built?

I am using an npm package (aurelia-google-maps) in my application. The package ships with AMD, System, CommonJS, Native Modules, and ES2015 dist folders like this:
/node_modules/
/aurelia-google-maps/
/dist/
/amd
/system
/native-modules
/es2015
/commonjs
In my typescript app I am simply importing all the classes and functions as:
import {Configure} from "aurelia-google-maps"
Is there a way that I can find out which distribution is used when I build my application?
I don't think you can determine it without the help of your build tool. It can be done in 2 steps:
using type of to check the availability of a variable in runtime code:
const distType = typeof DIST_TYPE !== 'undefined' ? DIST_TYPE : void 0;
configure the build tool to replace DIST_TYPE with the distribution target
And then you can use it in normal code, via distType variable.
For typescript, you just need an extra declaration
declare const DIST_TYPE: string | undefined;
I have figured it out. It seems like Aurelia automatically registers it's own plugin called DistPlugin that resolves dependencies using the native-modules folder. See this wiki for an explanation on how to change this behaviour.

Loading Nodejs Module at runtime in electron app

Currently I am playing around with electron using vue-cli-plugin-electron-builder along side a simple vue project. This is the project https://github.com/nklayman/vue-cli-plugin-electron-builder .
vue create my-project
cd my-project
vue add electron-builder
npm run electron:serve
My goal is to add a simple plugin-like architecture. The app serves only base functionality but can be extended with "plugins". Those plugins therefore are not included in the built, but will be loaded at runtime by electron. I would prefere when those plugins just behave like node modules ( module.exports = ) with its own dependencies ( probably with a package.json file inside ). I would locate those plugins at app.getPath('userData') + '/Plugins.
I looked at a few approaches on how to tackle this problem :
1. Using Nodejs vm module
First, I tried using Nodejs vm module to read and execute a script from an external file, all at runtime. It works great so far, although I would not be able to use external dependencies inside those loaded scripts. If I want to use external dependencies inside the plugin scripts, those dependencies must have been included in the electron build beforehand. Somehow defeats the whole purpose of having plugins ... only vanilla js + nodejs base modules would be possible .
2. using global.require
I saw this solution in another SO answer.
Using node require with Electron and Webpack
Webpack/electron require dynamic module
They say to use global.require but it throws an error saying global.require is not a function. The solution looked promising first, but somehow I can't get it to work.
3. simply use require
Of course I had to try it. When I try to require an external module from a non-project location it won't find the module, even if the path is correct. Again, the path I am trying to locate the module should be at app.getPath("userData"), not in the projects root directory. When however, I locate the plugins inside the root directory of the project it gets included in the built. This again defeats the purpose of having plugins.
Goal
So far, I haven't found a viable solution to this. I simply want my electron app to be extendible with basic node modules at runtime ( following a pre-defined schema to simplify ) . Of course there is atom, made with electron, using their own apm manager to install and load plugins, but this seems way to overpowered. Its enough for me to only have plugin files located locally, to have a public "marketplace" is no goal. Also, it's ok if the app has to reload / restart to load plugins.
Any ideas ?
After more and more research I stumbled over 2 packages :
https://www.npmjs.com/package/live-plugin-manager
https://github.com/getstation/electron-package-manager
both integrating npm to programmatically handle package installation at runtime. I settled for live-plugin-manager for now since its better documented and even allow package installation from local file system.
Pro
I was able to integrate the system out-of-the-box into a vanilla electron app. Works like a charm.
Cons
.I was not able to use it inside a vue electron boilerplate (like the one I said I was using in OP), since webpack is interferring with the require environment. But there sure is a solution to this.
Update : I was able to get it to work eventually inside a webpack bundled electron vue boilerplate. I accidentally mixed import and require . The following code works for me using live-plugin-manager
// plugin-loader.js
const path = require('path');
const { PluginManager } = require('live-plugin-manager');
const pluginInstallFolder = path.resolve(app.getPath('userData'), '.plugins');
const pluginManager = new PluginManager();
module.exports = async (pkg) => {
// installs pkg from npm
await pluginManager.install(pkg);
const package = pluginManager.require(pkg);
return package
}
// main.js
const pluginLoader = require('./plugin-loader');
pluginLoader("moment").then((moment) => {
console.log(moment().format());
})
This will install "moment" package from npm during runtime into a local directory and load it into the app, without bundling it into the executable files.

How to include dependencies in J2V8

How to include dependencies in J2V8? I would like to use certain dependencies in the javascript file for instance the crypto package.
var crypto = require('crypto');
function foo(){ return crypto.createHash('md5').update('Apple').digest("hex");}
However, I got the following error saying require keyword is undefined.
undefined:1: ReferenceError: require is not defined
var crypto = require('crypto');
^
ReferenceError: require is not defined at <anonymous>:1:14
com.eclipsesource.v8.V8ScriptExecutionException
at com.eclipsesource.v8.V8._executeVoidScript(Native Method)
Can anyone tell me how to import an package into J2V8?
Unless you're working with Node, require is not a feature. Usually, you want to use a bundler like webpack to pack your structured source code into one large file so that it can be understood by browsers. This way you can use require and npm packages for your frontend code, which makes development easier, and a bundler turns it with every build (or live update) into a different format, that's hard to read for humans, but is valid Javascript.
I have had success using node modules in J2v8, please check out this blog :http://eclipsesource.com/blogs/2016/07/20/running-node-js-on-the-jvm/
NodeJs nodeJS = NodeJs.createNodeJs();
After registering callbacks
nodeJs.exec(File thescripttoexecute)
Make sure you have the proper path to the node modules in the require() command.
You may have to make a nodejs package that takes dependencies and exports what you need. Then, You have to execute npm install manually.
or You can just npm install what-you-need.
Create Node JS Runtime, and use require with your your-package-dir/index.js or exact location of module that you need. like this:
V8Object module = nvm.require(file);
Now you can call the function likes:
module.executeJSFunction("test");
To deliver entire dependencies you have to bundlize module directory your self.
What if you have to support cross-platform, refer https://www.npmjs.com/package/node-pre-gyp also.

Browserify - JsSip

I have a new project where I'm using browserify to convert node modules into an sdk that can run inside the browser.
I'm requiring a number of other npm packages like:
var log4js = require('log4js');
That run fine and give me no problems in the browser, however JsSip just will not cooperate. When I do
var JsSIP = require('jssip');
I get
plivowebsdk.js:2 Uncaught Error: Cannot find module '../../package.json'
Looking through the code, it's obvious when it makes this call
var pkg = require('../../package.json');
is where it bombs out. Clearly it cannot find the package.json file, which it uses to pull out version information. I know JsSip is actually built with browersify itself (or used to be) so that it can run in either node or a browser. Is this causing a conflict?
Still sort of new to browserify, is their a configuration option or transformation I can perform to get around this?
Turned out the be browserify errors, re did the build process using the gulp recipes for browersify and works as expected.

Trying to use axios to make API call in a React/Phoenix App (using Brunch)

I'm trying to make use of the axios library to call some API endpoints.
My project setup is a Phoenix app (with brunch for asset management) and a React app (all in the web/static/js directory)
Most npm modules are ok, I do:
npm install --save _module-name_
Then I add the module to the brunch-config.js into the npm whitelist array.
Which I've done with axios, so it doesn't complain that it cannot find the library.
However, when I try and use axios e.g axios.post
I get the following error in the JS Console:
Cannot find module "axios/lib/adapters/xhr"
It's like brunch isn't loading in the axios dependencies (even though I can see that file if i navigate to node_modules/axios/lib/adapters
Has anyone had this issue (with any npm module and brunch/phoenix) and if so how do you go about fixing it?
Update
It seems to be a wider spread problem with brunch.
I also cannot use "React-Bootstrap" I get a similar error where it cannot find the sub-dependencies....
I had the same issue and updated brunch to the latest (2.7.5 at the time), which resolved my issue.
See https://github.com/brunch/brunch/issues/1136

Resources