How to require module only if exist. React native - javascript

Example:
let tmp;
try {
tmp = require('module-name');
} catch(e) {
return;
}
I get error (react native Metro Bundler):
error: bundling failed: Error: Unable to resolve module `module-name` from ...
How to require "module-name" only if exist?

That's what works for me:
let myPackage;
const myPackageToRequire = 'my-package-to-require';
try {
myPackage = require.call(null, myPackageToRequire);
} catch (e) {}
The variable definition const myPackageToRequire = 'my-package-to-require'; is necessary here.
Hope I helped.

Loading optional dependencies via try-catch has been added in Metro 0.59, which in turn means that you should be able to use your original code in React Native 0.63 if you turn it on in metro.config.js:
module.exports = {
transformer: {
allowOptionalDependencies: true,
},
}

Use require.resolve which will return resolved file name.
function checkModuleAvailability (module) {
try {
require.resolve(module);
return true
} catch(e) {
console.log(`${module} not found`);
}
return false
}
const moduleAvailable = checkModuleAvailability(MODULE_NAME) // true or false

Related

hardhat getNamedAccounts() does not work properly

I'm following the course of 32 hours Learn Blockchain, Solidity, .. in Javascript and I'm stucked with an error that others have but they solve because typos ecc.
I'm pretty sure at this point that the problem is not there but so what is the problem? I have my configuration file:
namedAccounts: {
deployer: {
default: 0,
1:0, // I even with this but nothing change
},
},
And I'm running everything in the hardhat default network, and when from the 00-deploy-mock.js the script calls the function getNamedAccounts():
module.exports = async function ({getNamedAccounts,deployments}){
const {deploy,log} = deployments
const {deployer} = await getNamedAccounts()
log(deployer)
if(developmentChains.includes(network.name)){
log("Local network " + network.name +" deploying mocks....")
await deploy("VRFCoordinatorV2Mock",{
from: deployer,
log: true,
args: [BASE_FEE,GAS_PRICE_LINK]
})
log("Mocks deployed !")
log("--------------------------------------------------")
}
}
log(deployer) prints undefined. and It returns the error:
TypeError: Cannot read properties of undefined (reading 'length')
The same process but using ganache instead run fine.
I have the hardhat-deploy plugin installed and i'm using the command hardhat deploy.
Any ideas ?
const { ethers } = require("hardhat");
async function main() {
const AMOUNT = ethers.utils.parseEther("0.1"); //bignumber
const [deployer] = await ethers.getSigners();
const iWTH = await ethers.getContractAt(
"IWeth",
"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",
deployer
);
const tx = await iWTH.deposit({ value: AMOUNT });
await tx.wait(1);
const wethBalance = await iWTH.balanceOf(deployer.address);
console.log(`WETH OF ${deployer.address}:= WETH ${wethBalance / 10 ** 18} `);
}
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});
Try this this worked for me .instead of getNamedAccounts use
const [deployer] = await ethers.getSigners();
It's clear that deployer is not loaded properly.
This usually happens when you have not set up your module.exports in the file where you wrote the "getNamedAccounts()" function
in your hardhat-config.js file under the module.exports section please include the following feilds
namedAccounts: {
deployer: {
default: 0,
1: 0,
} } ,
also please ensure that the following imports are there
require("#nomiclabs/hardhat-waffle")
require("hardhat-gas-reporter")
require("#nomiclabs/hardhat-etherscan")
require("dotenv").config()
require("solidity-coverage")
require("hardhat-deploy")
although gas-reports and all are not necessary since you are fallowing the 31-hours course ....sooner or later you will be needing it
I guess it should work now
In Hardhat.config.js file
change getNamedAccounts to namedAccounts
namedAccounts: {
deployer: {
default: 0,
},
users: {
default: 1,
},
},
Also,
in deploy.js Make getNamedAccounts a function by adding
"()"
const { deployer } = await getNamedAccounts;
to
const { deployer } = await getNamedAccounts();

NodeJS: My jest spyOn function is not being called

I don't understand why my spy is not being used. I have used this code elsewhere and it has worked fine.
Here is my test:
const {DocumentEngine} = require('../documentEngine')
const fileUtils = require('../utils/fileUtils')
const request = {...}
const fieldConfig = {...}
test('If the Carbone addons file is not found, context is built with the carboneAddons property as an empty object', async () => {
const expectedResult = {
carboneAddons: {},
}
const fileExistSpy = jest
.spyOn(fileUtils, 'checkFileExists')
.mockResolvedValue(false)
const result = await docEngine.buildContext(request, fieldConfig)
expect(fileExistSpy).toHaveBeenCalledTimes(1)
})
Here is the code that it is being tested:
async function buildContextForLocalResources(request, fieldConfig) {
/* other code */
const addonFormatters = await getCarboneAddonFormatters()
const context = {
sourceJson,
addonFormatters,
documentFormat,
documentTemplateId,
documentTemplateFile,
responseType,
jsonTransformContext
}
return context
}
async function getCarboneAddonFormatters() {
const addOnPath = path.resolve(
docConfig.DOC_GEN_RESOURCE_LOCATION,
'library/addon-formatters.js'
)
if (await checkFileExists(addOnPath)) {
logger.info('Formatters found and are being used')
const {formatters} = require(addOnPath)
return formatters
}
logger.info('No formatters were found')
return {}
}
This is the code from my fileUtils file:
const fs = require('fs/promises')
async function checkFileExists(filePath) {
try {
await fs.stat(filePath)
return true
} catch (e) {
return false
}
}
My DocumentEngine class calls the buildContext function which in turn calls the its method getCarboneAddonFormatters. The fileUtils is outside of DocumentEngine class in a utilities folder. The original code I had this working on was TypeScript as opposed to this which is just NodeJS Javascript. The config files for both are the same. When I try to step through the code (VSCode debugger), as soon as I hit the line with await fs.stat(filePath) in the checkFileExists function, it kicks me out of the test and moves on to the next test - no error messages or warnings.
I've spent most of the day trying to figure this out. I don't think I need to do an instance wrapper for the documentEngine, because checkFileExists is not a class member, and that looks like a React thing...
Any help in getting this to work would be appreciated.

Clarifai api referenceerror : process is not defined

I get such an error on npm start on clarifai api
[1]: https://i.stack.imgur.com/pHRNz.png
Open bootstrap:27:
// Execute the module function
try {
var execOptions = { id: moduleId, module: module, factory: __webpack_modules__[moduleId], require: __webpack_require__ };
__webpack_require__.i.forEach(function(handler) { handler(execOptions); });
module = execOptions.module;
execOptions.factory.call(module.exports, module, module.exports, execOptions.require);
} catch(e) {
module.error = e;
throw e;
}
// Flag the module as loaded
module.loaded = true;
// Return the exports of the module
return module.exports;
}
and my App.js details;
const app = new Clarifai.App({
apiKey: '****',
})
///
onButtonSubmit = () => {
console.log('click')
app.models
.predict(
'45fb9a671625463fa646c3523a3087d5',
'https://samples.clarifai.com/metro-north.jpg'
)
.then(
function (response) {
console.log(response)
},
function (err) {
//
}
)
}
I am getting this error before render in console.log. what would be the reason?
Happy coding day! :)
As stated in the documentation you need to use Broserify. You are missing NodeJS globals. Please let us know if this does not work for you as this library is unfortunately not under active maintenance currently.

electron "MAIN" : requiring you own js file and call function from it

I'm can't understand some things here related to electron. I've been searching for hours for the magic answer but couldn't find anything.
My goal is simple. I don't want my main electron.js file to be 5000 lines long without any kind of organization so I'm trying to split the code into multiple js file that make sense.
My idea was to use import { someFunction1, someFunction2 } from './scripts/someScript' in my electron.js and then just creating that file with the arrow function in it and export them.
Then I could call the function as I want in the main file. However, it doesn't seem to be possible. I've read electronjs doesn't support ES6 syntax. I've read about Babel (But from what I read, it implies a bunch of additional configuration and I don't want to spend days trying to add this to the bunch of configuration that are already messy with electron + React (No boiler plate here). And I didn't find anything specifics for this combo.
Question is. Is this doable in 2021? Am I missing anything? What would you guys recommend?
File would look something like this:
import { someNodeModuleFunction } from 'someNodeModule';
const someFunction1 = () => {
return 1;
};
const someFunction2 = () => {
return 2;
};
export { someFunction1, someFunction2 }
EDIT
Here's the actual code I have a problem with. I still get
if the file is .js: "Must use import to load ES Module"
If the file is .mjs: "Cannot use import statement outside a module"
This script is simply using fs to create a directory:
DataManagement.mjs:
import { existsSync, mkdir } from 'fs';
const electron = require('electron');
const app = electron.app;
const documentFolder = app.getPath('documents');
const CreateDataDirectory = () => {
const mainPath = documentFolder + 'AppName'
if (!existsSync(mainPath)) {
mkdir(mainPath);
}
};
module.exports = { CreateDataDirectory }
Calling it like that in electron.js:
const { CreateDataDirectory } = require('./scripts/DataManagement.mjs');
[...]
CreateDataDirectory()
Not sure how dividing the code can be that hard. :)
You may need to use Node.js module syntax (require and module.exports) or Babel (code transpiler).
For example:
import { someNodeModuleFunction } from 'someNodeModule';
const someFunction1 = () => {
return 1;
};
const someFunction2 = () => {
return 2;
};
module.exports = { someFunction1, someFunction2 }
Using your module:
const { someFunction1, someFunction2 } = require ('./FILE.js');
// ...
You could use module.exports:
otherModule.js
const someFunction1 = () => {
return 1;
};
const someFunction2 = () => {
return 2;
};
module.exports = {
someFunction1,
someFunction2
};
main.js
const { someFunction1, someFunction2 } = require('otherModule.js');

Typescript Error code: 2366, Function lacks ending return statement and return type does not include 'undefined'

I am currently working on the server/database of my project. It is currently composed of Javascript, Typescript, MongoDB, Apollo-Server, and Express. The error above keeps coming up and I am not sure how to solve it. Here is the code I have on my index.ts file for my database folder.
import { MongoClient } from "mongodb";
import { Database, Listing, Booking, User } from '../lib/types';
const url = `mongodb+srv://${process.env.DB_USER}:${process.env.DB_USER_PASSWORD}#${process.env.DB_CLUSTER}.mongodb.net`;
export const connectDatabase = async (): Promise<Database> => {
try {
const client = await MongoClient.connect(url, { useNewUrlParser: true, useUnifiedTopology: true });
const db = client.db("main");
return {
bookings: db.collection<Booking>("bookings"),
listings: db.collection<Listing>("listings"),
users: db.collection<User>("users"),
};
} catch (error) {
console.log(error);
}
};
Any help would be greatly appreciated.
You're catching the error but then you're not returning anything from the function. That is why it's complaining. Either remove the try/catch and handle the error in the function calling this one or return something usable to the caller.
Set "noImplicitReturns" to false in tsconfig.json.

Categories

Resources