How to use tensorflow js in wecaht mini app web worker? - tensorflow.js

I want to use tensorflow js in wechat mini app. And I also wanto to use web worker in wechat mini app to improve performance.
but, I find if I import tensorflow js in worker index js, console will print [worker] Uncaught Error: Could not find a global object.
How should I to fix it?
TensorFlow.js 3.5.0
tfjs-wechat plugin 0.0.6
WeChat IDE 1.06.2210310 (M1 Arm)
step to reapper:
package.json:
"dependencies": {
"#tensorflow-models/face-landmarks-detection": "^0.0.3",
"#tensorflow/tfjs-backend-webgl": "^3.5.0",
"#tensorflow/tfjs-converter": "^3.5.0",
"#tensorflow/tfjs-core": "^3.5.0",
"#tensorflow/tfjs-backend-cpu":"^3.6.0",
"abab": "2.0.0",
"base64-js": "1.3.1",
"fetch-wechat": "0.0.3",
"text-encoder": "0.0.4"
}
npm install & use build npm
we need to remove the tr46 package, otherwise the program will not be compiled by the applet
prepare workers file
I do this as doc describe: https://developers.weixin.qq.com/miniprogram/dev/framework/workers.html
copy the miniprogram_npm to workers/request dir
edit workers/request/index.js like this:
const tf = require('./miniprogram_npm/#tensorflow/tfjs-core/index')
worker.onMessage(res => {
console.log("worker 收到的 res: ", res)
})
send message to worker in app.js
const worker = wx.createWorker('workers/request/index.js')
worker.postMessage({
msg: "hello"
})
then the work will report [worker] Uncaught Error: Could not find a global object.
but if we add tr46 package in workers/request/miniprogram_npm, the work will compile error because heap memory overflow. like this:

Related

Meteor ionic 5 react

I have installed ionic in meteor 1.10 and importing ionic components gives me this error
Cannot read property 'dynamicImport' of undefined
the app code has nothing
import React from "react";
import {IonApp} from "#ionic/react";
export const App = () => (
<IonApp>
test
</IonApp>
);
I have not worked with Meteor but I suppose it is some problem of the way that imports the components
Any idea how to fix it ??
I ran into this same issue when upgrading to Meteor 1.10 in our app which uses ionic 5 and we were able to work around the issue by causing Meteor to package the commonjs version of ionic instead of the ES5 version.
The solution was to update the package.json in the #ionic/core loader and specify the common js entry point for the “browser” build (which the Meteor build tool will favor).
app/node_modules/#ionic/core/loader/package.json
{
"name": "ionic-loader",
"typings": "./index.d.ts",
+ "browser": "./index.cjs.js",
"module": "./index.mjs",
"main": "./index.cjs.js",
"node:main": "./node-main.js",
"jsnext:main": "./index.es2017.mjs",
"es2015": "./index.es2017.mjs",
"es2017": "./index.es2017.mjs",
"unpkg": "./cdn.js"
}
We’re tracking that one file in our repository as well in case we need to update (or reinstall) npm packages and the change gets undone.

react doesn't work on android kitkat 4.4.4 webview

i made an application with react, it works fine in chrome but when i try to run it with a browser that has a kiosk option, i get "Uncaught ReferenceError: Map is not defined".
i tried the solution provided in the documentation but still no success, so i made another application just for test and i got this error : "SyntaxError: Use of const in strict mode".
first project created with "react": "^16.8.6",
second project created with "react": "^16.9.0",
device is Samsung Galaxy Tab E.
browser is kiosk browser lockdown :
https://play.google.com/store/apps/details?id=com.procoit.kioskbrowser&hl=en
this is the solution i've tried but didn't work : https://reactjs.org/docs/javascript-environment-requirements.html

babel and reactjs: how to use es2015 style imports

I'm new to javascript and javascript build scripts, and I'm trying to build a "future-proof" build script for building a ReactJS/Redux app. I'm having trouble with getting imports to work between javascript files.
My question is what is the recommended approach to add support for es2016-style import statements?
As I've been trying to get this working, these are the questions and comments that are rolling around in my head that help color where I'm coming from.
I've just been getting a little more comfortable with Gulp. Is it possible to use just Gulp, Babel, and npm to add support for es2016-style import statements?
I'm wondering if Gulp still the recommended way to go for building javascript bundles, or should I learn WebPack instead.
In the past, I've used to use Browserify for including other javascript files, but I've heard people mention that you can do what Browserify does with pure npm and that Browserify may be falling out of favor.
I've noticed a lot of ReactJS examples using WebPack. I'm not sure where WebPack fits in or if it's necessary. I'm wondering if WebPack takes the place of Browserify and if I need WebPack or if I can do without it.
I'd prefer to use whatever import syntax is the recommended. I believe that Browserify uses require() and es2015 syntax uses "import ... from". I'm wondering if the "import ... from" is the recommended syntax to use for imports now or if I should be using something else.
I've been trying to use Babel 6 to use es2015-style code. I've noticed that it doesn't pre-process the import statements and I think I read somewhere that Babel 6 removed support for import statements. I'm wondering what to use in place of that to pre-process import statements.
I'd be interested in minimizing the amount of configuration (dot files and such) to build a basic project.
Below is a simple example that I've been trying to get working, using Gulp. Currently, when Gulp runs, is creates a bundle, but the import statement doesn't seem to work. When I try to load index.html, everything looks concated together and I get javascript errors.
more package.json
{
"name": "test_jsx",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"babel-cli": "^6.14.0",
"babel-plugin-transform-react-jsx": "^6.8.0"
},
"devDependencies": {
"babel-preset-es2015": "^6.14.0",
"babel-preset-react": "^6.11.1",
"babel-preset-stage-0": "^6.5.0",
"gulp": "^3.9.1",
"gulp-babel": "^6.1.2",
"gulp-cli": "^1.2.2",
"gulp-concat": "^2.6.0",
"gulp-print": "^2.0.1",
"gulp-sourcemaps": "^1.6.0"
}
}
more gulpfile.js
var gulp = require("gulp");
var print = require('gulp-print');
var sourcemaps = require("gulp-sourcemaps");
var babel = require("gulp-babel");
var concat = require("gulp-concat");
const paths = {
src: 'src/**/*js',
dest: 'build'
}
gulp.task("default", function () {
return gulp.src(paths.src)
.pipe(print())
.pipe(sourcemaps.init())
.pipe(babel({ presets: ['react', 'es2015', ]}))
.pipe(concat("bundle.js"))
.pipe(sourcemaps.write("."))
.pipe(gulp.dest("dist"));
});
more src/test.js
// This import statement is what I'm trying to get working.
import { square } from './lib';
var profile = <div>
<img src="avatar.png" className="profile" />
<h3>{[user.firstName, user.lastName].join(' ')}</h3>
</div>;
more src/lib.js
// This is just a example function that I want to try to import
export function square(x) {
return x * x;
}
more index.html
<script src="dist/bundle.js"></script>
TEST
Build steps
npm install
./node_modules/.bin/gulp
You can use either webpack or browserify to build your bundle, but they'll both be leveraging babel to provide ES6 support. I am not sure where you read that Babel 6 removed the import statement - I use Babel 6 and have had no such issue. You can build the bundle with gulp too but I find it's more work and tends to be harder to maintain. But, you might be getting a lot of opinionated answers here.
There is a tool that was provided by Facebook recently to bootstrap a React app without having to configure build tools: Create React App. You might want to either try that or one of the available boilerplate starters on Github, unless you like tinkering with build scripts. It's less flexible but if you are looking to reduce the amount of configuration it does the job.

Unable to require Parse in react-native. 'Requiring unknown module "react-native"'

I have the following installed with npm:
"dependencies": {
"parse": "^1.9.1",
"react-native": "0.32.0",
"react-native-admob": "^1.1.5",
"react-redux": "4.4.5",
"redux": "3.5.2"
},
I am unable to require Parse into my react-native app by using: var Parse = require('parse/react-native')
I get this error:
The file react-native IS inside node_modules/parse/react_native.js but my app wont find it. I have tried reseting the emulator, deleting and reinstalling node_modules.
The error is now a know issue: Issue
Solution:
Inside file node_modules/parse/lib/react-native/StorageController.react-native.js change this line:
var _reactNative = require('react-native');
to
var _reactNative = require('../../../react-native');
This is still an open issue in github:
This solution was found by #jaredwitt
In:
https://github.com/ParsePlatform/Parse-SDK-JS/issues/342
I was able to patch it by changing the following line in node_modules/parse/lib/react-native/StorageController.react-native.js

Requiring unknown module "crypto" in react-native environment

I'm writing a simple Twitter app using react-native. Using twit module to get twitter feeds and stream. Below is the code, it works fine node. However, when included into my react-native app, seeing error "Requiring unknown module "crypto"". Dependency seems to be myapp->twit->oauth->crypto (thats part of node v0.12.2). Any suggestions to get this working inside react-native environment?
var Twit = require('twit')
var T = new Twit({
consumer_key:''
, consumer_secret:''
, access_token:''
, access_token_secret:''
})
var filtered_tweets=[];
var error;
var isSuccess=false;
function getTweets(searchString){
T.get('search/tweets',{q:searchString, count:100}, getResponse);
}
function getResponse(err,data,response){
if(err) {
handleGetErr(err);
}
handleGetData(data.statuses);
}
function handleGetErr(err){
enter code here
error = err;
}
function handleGetData(data){
data.map(function(tweet){
var twit={
twit:tweet.id,
created_at:tweet.created_at,
text:tweet.text,
retweet_count:tweet.retweet_count,
favorite_count:tweet.favorite_count
};
filtered_tweets.push(twit);
});
console.log(filtered_tweets);
isSuccess=true;
}
getTweets("#sahaswaranamam");
module.exports = getTweets;
![attached][2]
The crypto module is a built-in Node module; React Native runs JS on JavaScriptCore (when on the device or simulator) and on Chrome itself (when using Chrome debugging), so modules that depend on built-in Node.js modules won't work. See the JavaScript Runtime section of the React Native docs for more info.
I'm not sure how hard it would be to integrate into a React Native app, but browser module bundlers like Browserify often have browser versions of core Node.js modules, like this one for crypto.
If you are using rn-nodeify as #emmby suggests, then you can use react-native-crypto. Instructions from the README:
Install
npm i --save react-native-crypto
# install peer deps
npm i --save react-native-randombytes
react-native link react-native-randombytes
# install latest rn-nodeify
npm i --save-dev mvayngrib/rn-nodeify
# install node core shims and recursively hack package.json files
# in ./node_modules to add/update the "browser"/"react-native"
# field with relevant mappings
./node_modules/.bin/rn-nodeify --hack --install
rn-nodeify will create a shim.js in the project root directory
// index.ios.js or index.android.js
// make sure you use `import` and not require!
import './shim.js'
// ...the rest of your code
But rn-nodeify also states:
If you're looking for a saner approach, check out ReactNativify. I haven't tested it myself, but I think philikon will be happy to help
With ReactNativify you create a rn-cli.config.js and then in a transformer.js you let Babel transform bundle dependencies using babel-plugin-rewrite-require:
// The following plugin will rewrite imports. Reimplementations of node
// libraries such as `assert`, `buffer`, etc. will be picked up
// automatically by the React Native packager. All other built-in node
// libraries get rewritten to their browserify counterpart.
[require('babel-plugin-rewrite-require'), {
aliases: {
crypto: 'crypto-browserify',
// ...
},
throwForNonStringLiteral: true,
}]
(Note: You can also do this in without these 2 js files directly in .babelrc)
(Note2: Though ReactNativify is the cleaner way, it is still giving me issues wiring up crypto.getRandomValues for production-use in RN. See this question)
You can use the rn-nodeify module to get crypto on react-native.
Add rn-nodeify to your devDependencies in package.json:
"devDependencies": {
"rn-nodeify": "^6.0.1"
}
Add the following to the scripts section of the same file:
"scripts": {
…
"postinstall": "node_modules/.bin/rn-nodeify --install crypto --hack"
}
Be aware that rn-nodeify will modify your package.json.
More information available here: https://www.npmjs.com/package/rn-nodeify
React Native packager uses Babel under the hood. This means that you can use babel-plugin-rewrite-require Babel plugin to rewrite all require('crypto') calls to require('crypto-browserify'), assuming that the latter is installed in your node_modules.
As of January 2016, you can use .babelrc file to define optional configuration, so this becomes really easy. First, install the dependencies:
npm install --save crypto-browserify
npm install --save-dev babel-plugin-rewrite-require
Then add plugins config to your .babelrc file:
{
"presets": ["react-native"],
"plugins": [
["babel-plugin-rewrite-require", {
"aliases": {
"crypto": "crypto-browserify"
}
}]
]
}
Restart the packager and that should be it.
This is the same approach that ReactNativify uses, except that here we use .babelrc instead of defining custom transformer. When ReactNativify was written, it was not supported, so they had to go with more complex solution. See this file from ReactNativify for almost complete list of node polyfills.
I was having the same issue when implementing the Twilio package in my React Native app, and having React Native break over the crypto dependency.
As a work around I ended up creating a separate, stand alone Node/Express app to act as my server and take care of the Twilio logic I had. That way I removed all Twilio logic from my React Native app and moved it to Node. I then just called my Express route in React Native using fetch, which triggered the functionality I wanted to happen with Twilio. If you're unfamiliar with fetch here's a good starting point -
Making AJAX calls with Fetch in React Native
In addition, here's my question on the crypto dependency breaking my app:
twilio-react-native-unable-to-resolve-module-crypto
As far I can see amazon-cognito-identity-js uses crypto-js 3.3.0 without any additional magic... If that version of the package works then perhaps try that.
After having tried a bunch of these solutions and never really having been satisfied with any of them (some didn't even work), I managed to stumble upon react-native-quick-crypto, which honestly worked much more effortlessly than trying to lift the existing crypto library to the front-end

Resources