metro error 'crypto', package itself specifies a `main` module field that could not be resolved, react-native and open api - react-native

running react native with ios simulator.
the backend uses open api, and has a folder in FrontEnd, to enforce schemas. I'm calling a class from this openapi auto generated file Frontend/sdk/api.ts.
in my frontend/service/doSomething.ts,
import { DefaultApi } from '../sdk/api // in frontend, autogenerated by open API
function func1 () {
const api = new DefaultApi() // calls crypto somehow
}
on build, i get this error
BUNDLE ./index.js
error: Error: While trying to resolve module `crypto` from file
`/app/node_modules/request/lib/helpers.js`, the package
`/app/node_modules/crypto/package.json` was successfully found.
However, this package itself specifies a `main` module field that
could not be resolved (`/app/node_modules/crypto/index.js`. Indeed,
none of these files exist:
* /app/node_modules/crypto/index.js(.native|.ios.jsx|.native.jsx|.jsx|.ios.js|.native.js|.js|.ios.ts|.native.ts|.ts|.ios.tsx|.native.tsx|.tsx|.ios.json|.native.json|.json)
* /app/node_modules/crypto/index.js/index(.native|.ios.jsx|.native.jsx|.jsx|.ios.js|.native.js|.js|.ios.ts|.native.ts|.ts|.ios.tsx|.native.tsx|.tsx|.ios.json|.native.json|.json)
at DependencyGraph.resolveDependency (/app/node_modules/metro/src/node-haste/DependencyGraph.js:311:17)
at Object.resolve (/app/node_modules/metro/src/lib/transformHelpers.js:129:24)
at resolve (/app/node_modules/metro/src/DeltaBundler/traverseDependencies.js:396:33)
at /app/node_modules/metro/src/DeltaBundler/traverseDependencies.js:412:26
at Array.reduce (<anonymous>)
at resolveDependencies (/app/node_modules/metro/src/DeltaBundler/traverseDependencies.js:411:33)
at processModule (/app/node_modules/metro/src/DeltaBundler/traverseDependencies.js:140:31)
at processTicksAndRejections (internal/process/task_queues.js:95:5)
at async addDependency (/node_modules/metro/src/DeltaBundler/traverseDependencies.js:230:18)
at async Promise.all (index 2)
Failed: I've tried following However, this package itself specifies a `main` module field that could not be resolved adding to metro.config.js
resolver: {
sourceExts: ['jsx', 'js', 'ts', 'tsx'], //add here
}
but it FAILS with same error.

the request package and crypto has been deprecated.

Related

react native yalc nested gives : jest-haste-map: Haste module naming collision error

Let's see the error first:
jest-haste-map: Haste module naming collision: #stevemoretz/yoohoo
The following files share their name; please adjust your hasteImpl:
* <rootDir>/.yalc/#stevemoretz/yoohoo-ratchet-expo/.yalc/package-name2/package.json
* <rootDir>/.yalc/package-name1/package.json
Failed to construct transformer: DuplicateError: Duplicated files or mocks. Please check the console for more info
at setModule (/Volumes/HDD/ReactNative/upgrade/store/node_modules/jest-haste-map/build/index.js:543:17)
at workerReply (/Volumes/HDD/ReactNative/upgrade/store/node_modules/jest-haste-map/build/index.js:614:9)
at processTicksAndRejections (internal/process/task_queues.js:95:5)
at async Promise.all (index 27)
at /Volumes/HDD/ReactNative/upgrade/store/node_modules/jest-haste-map/build/index.js:426:22 {
mockPath1: '.yalc/package-name1/.yalc/#stevemoretz/yoohoo/package.json',
mockPath2: '.yalc/package-name2/package.json'
}
What's happening? I'm using a nested yalc package in another yalc package, so I get this error, how do I solve that?
Getting rid of .yalc folder, fixes this but we can't do that because yalc won't work well 🙂.
But we can exclude it from the metro bundler that fixes it, how?
https://stackoverflow.com/a/41963217/10268067
so in our case it becomes:
const exclusionList = require("metro-config/src/defaults/exclusionList");
// exclusionList is a function that takes an array of regexes and combines
// them with the default exclusions to return a single regex.
module.exports = {
resolver: {
blacklistRE: exclusionList([/.yalc\/.*/]),
},
};

How to Hide API key in Preact?

How can i hide api key in preact , in react i used .env file , but don't know how to do it in preact ?
index.js?2e9b:8 Uncaught (in promise) ReferenceError: process is not defined
at eval (index.js?2e9b:8)
at Generator.next (<anonymous>)
at asyncGeneratorStep (index.js:5)
at _next (index.js:7)
at eval (index.js:7)
at new Promise (<anonymous>)
at eval (index.js:7)
at getSeriesInfo (index.js?2e9b:7)
at Object.eval [as __] (index.js?2e9b:14)
at j (index.js?a178:361)
Preact is just a UI library, but I'll assume you're referring to Preact-CLI, which is an actual build tool. Let me know if this is incorrect.
Our wiki covers this under "Use Environment Variables in your Application". process will not exist outside of Node so you'll need to specify the variables you want to use using DefinePlugin.
Add the following to your preact.config.js file:
export default (config, env, helpers) => {
config.plugins.push(
new helpers.webpack.DefinePlugin({
'process.env.MY_VARIABLE': JSON.stringify('my-value'),
}),
);
};
If you specifically want to read from a .env file, you will also need to add some utility to read it, such as dotenv:
import dotenv from 'dotenv';
dotenv.config();
export default (config, env, helpers) => {
config.plugins.push(
new helpers.webpack.DefinePlugin({
'process.env.MY_VARIABLE': JSON.stringify(process.env.MY_VARIABLE),
}),
);
};

Set a custom entry file for Metro dev server in React Native build

I'm writing some scripts that do custom React Native builds for unit testing and such, specifying a custom entry file for the react-native-xcode.sh script using the ENTRY_FILE env variable. This is super useful and great. I'm able to do release builds no problem, and they work just fine, so basically I can build a RN app from any entry file at will. However, when I try a Debug variant build, metro doesn't seem to know about my special custom entry file, and gives me this error:
None of these files exist:
* index(.native|.ios.js|.native.js|.js|.ios.json|.native.json|.json|.ios.ts|.native.ts|.ts|.ios.tsx|.native.tsx|.tsx)
* index/index(.native|.ios.js|.native.js|.js|.ios.json|.native.json|.json|.ios.ts|.native.ts|.ts|.ios.tsx|.native.tsx|.tsx)
at ModuleResolver.resolveDependency (/Users/justin/dev/enmesh/testutilsnative/node_modules/metro/src/node-haste/DependencyGraph/ModuleResolution.js:165:15)
at ResolutionRequest.resolveDependency (/Users/justin/dev/enmesh/testutilsnative/node_modules/metro/src/node-haste/DependencyGraph/ResolutionRequest.js:52:18)
at DependencyGraph.resolveDependency (/Users/justin/dev/enmesh/testutilsnative/node_modules/metro/src/node-haste/DependencyGraph.js:285:16)
at /Users/justin/dev/enmesh/testutilsnative/node_modules/metro/src/lib/transformHelpers.js:267:42
at Server.<anonymous> (/Users/justin/dev/enmesh/testutilsnative/node_modules/metro/src/Server.js:841:41)
at Generator.next (<anonymous>)
at asyncGeneratorStep (/Users/justin/dev/enmesh/testutilsnative/node_modules/metro/src/Server.js:99:24)
at _next (/Users/justin/dev/enmesh/testutilsnative/node_modules/metro/src/Server.js:119:9)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
IN RESOLVER
Error: Unable to resolve module `./index` from ``:
Does anyone know how I can get the Debug build of the app to interface properly with the Metro development server, so I can debug my app builds better? Any guidance here would be greatly appreciated!
Metro is just getting launched automatically by the xcodebuild process, which I'm calling like this:
const args = {
simulator: device,
configuration: variant,
scheme,
projectPath: xcodeProjectPath,
device: undefined,
uuid: undefined,
packager: true,
verbose: true,
port: 8081,
terminal: undefined,
};
const xcodebuildSpawnOptionsArgs: any = {
...args,
cwd: folder,
env: {
PLATFORM: 'ios',
ENTRY_FILE: builtEntryFilePath,
},
};
const buildProcess = spawn(
'xcodebuild',
xcodebuildArgs,
getProcessOptions(xcodebuildSpawnOptionsArgs),
);

ReferenceError: ReadableStream is not defined while running jest tests

My web app reads local files using a custom ReadableStream (in-order that I won't need to have a max file size that the platform supports) and it works great, both for correctly formatted files and error files. My app is built using React-Redux-Saga.
I'm now attempting to add limited e2e tests to my code to test the state management. I'm testing that when sending redux actions the state updates correctly. I'm testing the saga's using the package redux-saga-tester.
While running the jest client tests that read local files using the ReadableStream I built, I got an error ReferenceError: ReadableStream is not defined. What I understood is that the jsdom environment that jest uses is missing the ReadableStream implementation. I than added the web-streams-polyfill package to polyfill the ReadableStream class.
Now the validate file test is passing as in the browser:
test('Select and validate log file', async () => {
const testFile = testFileBuilder.valid();
storeTester.dispatch(fileSelected(testFile));
await storeTester.waitFor(FILE_VALIDATED);
const state = storeTester.getState().file;
expect(state.fileValidated).toBeTruthy();
});
My problem is that when I run a second validation test with an invalid file the test passes but prints an error to the console.
The test:
test('Select an invalid file - JSON error', async () => {
const testFile = testFileBuilder.errorJSON();
storeTester.dispatch(fileSelected(testFile));
await storeTester.waitFor(FILE_ERROR);
const state = storeTester.getState().file;
expect(state.fileValidated).toBeFalsy();
expect(state.fileError).toBeTruthy();
});
The error that is printed after the test completes successfully:
e.error node_modules/jsdom/lib/jsdom/virtual-console.js:29
Error: Error: connect ECONNREFUSED 127.0.0.1:80
at Object.dispatchError (/home/noams/dev/web/visual-log-viewer/client/node_modules/jsdom/lib/jsdom/living/xhr-utils.js:65:19)
at Request.client.on.err (/home/noams/dev/web/visual-log-viewer/client/node_modules/jsdom/lib/jsdom/living/xmlhttprequest.js:676:20)
at Request.emit (events.js:194:15)
at Request.onRequestError (/home/noams/dev/web/visual-log-viewer/client/node_modules/request/request.js:881:8)
at ClientRequest.emit (events.js:189:13)
at Socket.socketErrorListener (_http_client.js:392:9)
at Socket.emit (events.js:189:13)
at emitErrorNT (internal/streams/destroy.js:82:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:50:3)
at process._tickCallback (internal/process/next_tick.js:63:19) undefined
Any subsequent file validation tests fail.
I'd appreciate any advice of how to tackle this issue.

React Native MQTT Module `url` does not exist in the Haste module map

I want to explore this project https://github.com/mqttjs/MQTT.js within the React Native environment. So I did this:
react-native init myproject
npm install --save mqtt
Then I pasted this sample code from the mqttjs into my App.js a bit after the "Welcome to React Native" component.
var mqtt = require('mqtt')
var client = mqtt.connect('mqtt://test.mosquitto.org')
client.on('connect', function () {
client.subscribe('presence', function (err) {
if (!err) {
client.publish('presence', 'Hello mqtt')
}
})
})
client.on('message', function (topic, message) {
// message is Buffer
console.log(message.toString())
client.end()
})
But when I run react-native run-android, I get a compilation error with a message like
Module url does not exist in the Haste module map
I tried replacing mqtt://test.mosquitto.org with a url to my own mosquitto broker with some of these values: mqtt://192.168.0.20, tcp://192.168.0.20, 192.168.0.20. But all these still generated the same error.
What am I doing wrong?
You can solve this by explicitly installing the url module:
npm install url