__scanCodes is not defined vision-camera-code-scanner [React Native] - react-native

I'm getting the following error, as a lot of other people report on issues.
__scanCodes is not defined
It occurs both on iOS and Android.
Here's my libraries version:
"react-native": "^0.70.6",
"react-native-vision-camera": "^2.15.2",
"vision-camera-code-scanner": "^0.2.0",
"react-native-reanimated": "^2.13.0",
And finally the babel.config.js
module.exports = {
presets: ["module:metro-react-native-babel-preset"],
plugins: [
["react-native-reanimated/plugin", { globals: ["__scanCodes"] }],
"module:react-native-dotenv",
],
};
I have also tried to patch react-native-vision-camera, following this instructions:
https://github.com/rodgomesc/vision-camera-code-scanner/issues/79#issuecomment-1278937809
Here's the code I'm using:
const [frameProcessor, barcodes] = useScanBarcodes([BarcodeFormat.QR_CODE], { checkInverted: true });
And here's the Xcode error:
Developer/Xcode/DerivedData/Real-cktefjzimocjmeeqhtpyfxgfpixu/Build/Products/Debug-iphoneos/vision-camera-code-scanner/vision_camera_code_scanner.modulemap' not found
Does someone have a solution for this issue? Or does a patch exist to solve the problem?
Thank you

I had the same issue, I don't know why useScanBarcodes hook is not working. Working solution is like:
import {
Camera,
useCameraDevices,
useFrameProcessor,
} from 'react-native-vision-camera';
import { scanBarcodes, BarcodeFormat } from 'vision-camera-code-scanner';
const CameraView = () => {
const devices = useCameraDevices();
const device = devices.back;
const frameProcessor = useFrameProcessor(
frame => {
'worklet';
const detectedBarcodes = scanBarcodes(frame, [BarcodeFormat. QR_CODE], {checkInverted: true });
const barcode = detectedBarcodes[0];
if (barcode) { {
runOnJS(setBarcodes)(barcode);
}
},
[],
);
return (
<CameraView
device={device}
isActive={true}
frameProcessor={frameProcessor}
frameProcessorFps={5}
orientation="portrait"
/>
)
}

Related

React native couldn't resolve local module after noHoist has been added to project

I have this monorepo js setup with yarn workspaces and lerna
/package.json
/packages
/common (js shared code)
/package.json
/mobile (react native - metro)
/package.json
/web (CRA)
/package.json
Mobile and web packages are importing common package inside package.json as follow
"dependencies": {
"common": "*",
}
I had to add noHoist option in root package.json so that mobile native dependencies don't get hoisted so build scripts still run fine
"workspaces": {
"packages": [
"packages/*"
],
"nohoist": [
"**/react-native",
"**/react-native/**"
]
}
Web did work fine before and after adding noHoist option
React native metro bundling start failing after adding noHoist .. it shows
"Error: Unable to resolve module .. could not be found within the project or in these directories:
node_modules
../../node_modules"
However common package does actually exists under root node_modules ?
Looks like some kind of a linking issue ! (did try to link it manually/ same issue) .. note that I didn't add common package under noHoist
here how my metro config looks like
const path= require('path');
const watchFolders = [
path.resolve(`${__dirname}`), // Relative path to package node_modules
path.resolve(`${__dirname}/../../node_modules`), // Relative path to root node_modules ];
module.exports = {
transformer: {
getTransformOptions: async () => ({
transform: {
experimentalImportSupport: false,
inlineRequires: true,
},
}),},
maxWorkers: 2,
watchFolders, };
ANY IDEA ? 🧐
Turns out the issue was in bundling, fixed by editing metro.config.js to include blocklist and extraNodeModules
const path = require('path');
const exclusionList = require('metro-config/src/defaults/exclusionList');
const getWorkspaces = require('get-yarn-workspaces');
function generateAssetsPath(depth, subpath) {
return `/assets`.concat(
Array.from({ length: depth })
// eslint-disable-next-line no-unused-vars
.map((_, i) => `/${subpath}`)
.join(''),
);
}
function getMetroAndroidAssetsResolutionFix(params = {}) {
const { depth = 3 } = params;
let publicPath = generateAssetsPath(depth, 'dir');
const applyMiddleware = (middleware) => (req, res, next) => {
// eslint-disable-next-line no-plusplus
for (let currentDepth = depth; currentDepth >= 0; currentDepth--) {
const pathToReplace = generateAssetsPath(currentDepth, 'dir');
const replacementPath = generateAssetsPath(depth - currentDepth, '..');
if (currentDepth === depth) {
publicPath = pathToReplace;
}
if (req.url.startsWith(pathToReplace)) {
req.url = req.url.replace(pathToReplace, replacementPath);
break;
}
}
return middleware(req, res, next);
};
return {
publicPath,
applyMiddleware,
};
}
function getNohoistedPackages() {
// eslint-disable-next-line global-require
const monorepoRootPackageJson = require('../../package.json');
const nohoistedPackages = monorepoRootPackageJson.workspaces.nohoist
.filter((packageNameGlob) => !packageNameGlob.endsWith('**'))
.map((packageNameGlob) => packageNameGlob.substring(3));
return nohoistedPackages;
}
function getMetroNohoistSettings({
dir,
workspaceName,
reactNativeAlias,
} = {}) {
const nohoistedPackages = getNohoistedPackages();
const blockList = [];
const extraNodeModules = {};
nohoistedPackages.forEach((packageName) => {
extraNodeModules[packageName] =
reactNativeAlias && packageName === 'react-native'
? path.resolve(dir, `./node_modules/${reactNativeAlias}`)
: path.resolve(dir, `./node_modules/${packageName}`);
const regexSafePackageName = packageName.replace('/', '\\/');
blockList.push(
new RegExp(
`^((?!${workspaceName}).)*\\/node_modules\\/${regexSafePackageName}\\/.*$`,
),
);
});
return { extraNodeModules, blockList };
}
const workspaces = getWorkspaces(__dirname);
const androidAssetsResolutionFix = getMetroAndroidAssetsResolutionFix({
depth: 3,
});
const nohoistSettings = getMetroNohoistSettings({
dir: __dirname,
workspaceName: 'mobile',
});
module.exports = {
transformer: {
// Apply the Android assets resolution fix to the public path...
// publicPath: androidAssetsResolutionFix.publicPath,
getTransformOptions: async () => ({
transform: {
experimentalImportSupport: false,
inlineRequires: true,
},
}),
},
// server: {
// // ...and to the server middleware.
// enhanceMiddleware: (middleware) =>
// androidAssetsResolutionFix.applyMiddleware(middleware),
// },
// Add additional Yarn workspace package roots to the module map.
// This allows importing importing from all the project's packages.
watchFolders: [
path.resolve(__dirname, '../../node_modules'),
...workspaces.filter((workspaceDir) => !(workspaceDir === __dirname)),
],
maxWorkers: 2,
resolver: {
// Ensure we resolve nohoisted packages from this directory.
blockList: exclusionList(nohoistSettings.blockList),
extraNodeModules: nohoistSettings.extraNodeModules,
},
};
You can check this universal CRA/RN mono-repo that uses such metro configs

Error: While trying to resolve module #apollo/client React Native

after installing new version of apollo client getting this Error. I tried other versions and to downgrade but nothing. Also I tried to specify in metro.config.js to resolve "cjs" type of file (#apollo/client/main.cjs), but nothing.
Error
error: Error: While trying to resolve module `#apollo/client` from file `****\src\api\queries\home.js`, the package `****\node_modules\#apollo\client\package.json` was successfully found. However, this package itself specifies a `main` module field that could not be resolved (`****\node_modules\#apollo\client\main.cjs`. Indeed, none of these files exist:
Dependencies
"#apollo/client": "^3.3.2",
"graphql": "^15.4.0",
Anyone can help me please? Will be very thankful!
As documented at https://github.com/apollographql/apollo-client/blob/main/CHANGELOG.md#apollo-client-354-2021-11-19, the solution should be to add
const { getDefaultConfig } = require("metro-config");
const { resolver: defaultResolver } = getDefaultConfig.getDefaultValues();
exports.resolver = {
...defaultResolver,
sourceExts: [
...defaultResolver.sourceExts,
"cjs",
],
};
in your metro.config.js.
In my case, I already have a module.exports generated by default, so I just had to make the file so:
const {getDefaultConfig} = require('metro-config');
const {resolver: defaultResolver} = getDefaultConfig.getDefaultValues();
module.exports = {
transformer: {
getTransformOptions: async () => ({
transform: {
experimentalImportSupport: false,
inlineRequires: true,
},
}),
},
resolver: {
...defaultResolver,
sourceExts: [...defaultResolver.sourceExts, 'cjs'],
},
};
Simply adding cjs file extension to metro.config.js works for me.
According to expo's Official Adding more file extensions to assetExts documentation...
const { getDefaultConfig } = require('#expo/metro-config');
const defaultConfig = getDefaultConfig(__dirname);
defaultConfig.resolver.assetExts.push('cjs');
module.exports = defaultConfig;
I have exactly the same problem in react-native.
From the documentation, it follows that you need to add the ability to handle "cjs" files.
https://github.com/apollographql/apollo-client/blob/main/CHANGELOG.md#apollo-client-354-2021-11-19
Solved the problem today by adding to node_modules/metro-config/src/defaults/defaults.js
export.sourceExts = ["js", "json", "ts", "tsx", "cjs"];
and from the project folder
for android:
cd android && ./gradlew clean
for ios in xcode :
clean -> run
For Expo Projects, We need to add cjs to sourceExts.
const { getDefaultConfig } = require('#expo/metro-config');
const defaultConfig = getDefaultConfig(__dirname);
defaultConfig.resolver.sourceExts.push('cjs');
module.exports = defaultConfig;
Apollo Docs for source extension https://github.com/apollographql/apollo-client/blob/main/CHANGELOG.md#apollo-client-354-2021-11-19
Expo syntax for metro config https://docs.expo.dev/guides/customizing-metro/

Unexpected string error in Jest with './environment/validate.fx';

In my React Native app, I'm just starting to write a test file, which runs fine like this:
// #flow
import type {
Location,
LocationAction
} from "../src/redux/reducers/locationReducer";
// import { getLocationSaga } from "../src/redux/actions/locationActions";
import SagaTester from "redux-saga-tester";
import recordSaga from "../recordSaga";
describe("getLocationAsync", () => {
const calculatedSimulatorLocation: Location = {
latitude: 37.33233141,
latitudeDelta: 0.0004491555874955085,
longitude: -122.0312186,
longitudeDelta: -0.05737702242408729
};
const startAction: LocationAction = { type: "USER_LOCATION_START" };
const successAction: LocationAction = {
type: "USER_LOCATION_SUCCESS",
region: calculatedSimulatorLocation
};
describe("userLocationSaga", () => {
it("gets the user's location", async () => {
const dispatched = await recordSaga(getLocationSaga, startAction);
expect(dispatched).toContainEqual(successAction);
});
});
});
The test, of course, fails because getLocationSaga is not defined. I've stubbed the function in my actions file:
// #flow
import { Location } from "expo";
import type { LocationAction } from "../reducers/locationReducer";
import type { Saga } from "redux-saga";
export function getLocationAsync(): LocationAction {
return { type: "USER_LOCATION_START" };
}
export function* getLocationSaga(): Saga<void> {
return console.log("hello from saga");
}
But when I uncomment the line in the tests that imports this method, I get this error:
● Test suite failed to run
/Users/TuzMacbookPro2017/Development/QMG-local/APPS/QMGTrago/node_modules/expo/build/Expo.fx.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import './environment/validate.fx';
^^^^^^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: Unexpected string
at ScriptTransformer._transformAndBuildScript (node_modules/#jest/transform/build/ScriptTransformer.js:471:17)
at ScriptTransformer.transform (node_modules/#jest/transform/build/ScriptTransformer.js:513:25)
at Object.<anonymous> (node_modules/expo/src/Expo.ts:1:1)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 7.506s
Ran all test suites.
Watch Usage: Press w to show more.
How do I fix this? Below are some config files:
package.json
...
"jest": {
"preset": "react-native"
},
...
.eslintrc
{
"parser": "babel-eslint",
"extends": "airbnb",
"plugins": ["react", "jsx-ally", "import"]
}
babel.config.js
module.exports = function(api) {
api.cache(true);
return {
presets: ["babel-preset-expo", "#babel/preset-flow"]
};
};
I had this same issue today on a react-native/ expo app that is using jest. I referenced their guide at https://docs.expo.io/versions/latest/guides/testing-with-jest/. I looked at the following section listing the transform patterns to ignore:
"transformIgnorePatterns": [
"node_modules/(?!(jest-)?react-native|react-clone-referenced-element|#react-native-community|expo(nent)?|#expo(nent)?/.*|react-navigation|#react-navigation/.*|#unimodules/.*|sentry-expo|native-base)"
]
This is found in jest config file (mine is jest.config.js). I noticed mine was missing the following: |#unimodules/.*|sentry-expo|expo(nent)?|#expo(nent)?/.*|
I included those to fix that specific error.
However, I then got the following errors :
The Expo SDK requires Expo to run. It appears the native Expo modules are unavailable and this code is not running on Expo.
I discovered that I needed to configure my jest to work with jest-expo according to the docs.

How do you enable 'require(*/*.vrx)' using rn-cli.config?

The Metro bundler for react-native cli is unable to resolve a .vrx file (used for a viroreact AR scene).
I've tried to create an rn-cli.config.js file in the project root that should have sorted it but it isn't. What am I missing?
I've tried to create an rn-cli.config.js file in the project root that should have sorted it but it isn't. What am I missing?
The path specified is definitely correct in the requiring .js
rn-cli.config.js
const { getDefaultConfig } = require("metro-config");
module.exports = (async () => {
const {
resolver: { assetExts }
} = await getDefaultConfig();
return {
resolver: {
assetExts: [...assetExts, "obj", "mtl", "JPG", "vrx", "fbx", "hdr"]
}
};
})();
Metro bundler reporting this error
error: bundling failed: Error: Unable to resolve module `./js/res/coffee_mug/object_coffee_mug.vrx` from `C:\Users\Dave\Documents\schoolOfCode\Final Project\final-project-app-brumgo-front-end\components\ARtest\index.js`: The module `./js/res/coffee_mug/object_coffee_mug.vrx` could not be found from `C:\Users\Dave\Documents\schoolOfCode\Final Project\final-project-app-brumgo-front-end\components\ARtest\index.js`. Indeed, none of these files exist:
Please update the metro.config.js at the root of your project as follows.
const {getDefaultConfig} = require('metro-config');
module.exports = (async () => {
const {
resolver: {assetExts},
} = await getDefaultConfig();
return {
resolver: {
assetExts: [
...assetExts,
'obj',
'mtl',
'JPG',
'vrx',
'hdr',
'gltf',
'glb',
'bin',
'arobject',
'gif',
],
},
};
})();

undefined is not an object (evaluating '_effects.buffers.expanding')

I'm getting an error when tried to copy&paste this solution in my app.
undefined is not an object (evaluating 'effects.buffers.expanding')
My code is pretty similar:
export function* handleBleState() {
const {
bleConnections: { manager },
} = yield select()
const stateChannel = yield eventChannel((emit) => {
const subscription = manager.onStateChange((state) => {
emit(state)
}, true)
return () => {
subscription.remove()
}
}, buffers.expanding(1))
try {
for (;;) {
const newState = yield take(stateChannel)
const power = newState === 'PoweredOn'
yield put(BLEActions.updateBleState(power))
}
} finally {
if (yield cancelled()) {
stateChannel.close()
}
}
}
But what is more strange is that I have extracted code from the documentation of redux-saga and the error is similar.
I replaced part of the code with this:
const stateChannel = yield eventChannel((emitter) => {
const iv = setInterval(() => {
secs -= 1
if (secs > 0) {
emitter(secs)
} else {
// this causes the channel to close
emitter(END)
}
}, 1000)
// The subscriber must return an unsubscribe function
return () => {
clearInterval(iv)
}
})
And I get:
undefined is not a function (evaluating '(0, _effects.eventChannel)')
I'm using another version of redux-saga:
"redux-saga": "^1.0.2",
But I tried with the same version that he use
"redux-saga": "0.16.2"
And then the issue is another one:
console.error: "unchaught at root", "at root at takeLatest" at handleBleState etc, etc.
Any help will be welcome, thanks in advance.
PD:
"react": "16.6.1",
"react-native": "0.57.5",
"react-native-ble-plx": "^1.0.1",
the eventChannel is nor part of the effects but defined directly in the main module, see the relevant API doc. So if you're using ES6 import/export you import it with the following statement:
import { eventChannel } from 'redux-saga'
While the require equivalent should be:
const eventChannel = require('redux-saga').eventChannel