I'm new with Mongo I'm doing a tutorial and I can make it work. I keep seeing this error on the console when I'm trying to import data.
> proshop#1.0.0 data:import
> node backend/seeder
the options [useCrateIndexes] is not supported
(node:40078) DeprecationWarning: collection.ensureIndex is deprecated. Use createIndexes instead.
(Use `node --trace-deprecation ...` to show where the warning was created)
MongoDB Connected: cluster0-shard-00-02.8p56h.mongodb.net
ValidationError: isAdmin: Path `isAdmin` is required.
npm ERR! code 1
npm ERR! path /Users/googledrive/Documents/proshop
npm ERR! command failed
npm ERR! command sh -c node backend/seeder
npm ERR! A complete log of this run can be found in:
npm ERR! /Users/googledrive/.npm/_logs/2021-01-14T00_02_04_851Z-debug.log
❯ node --trace-deprecation ...
node:internal/modules/cjs/loader:928
throw err;
^
Error: Cannot find module '/Users/googledrive'
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:925:15)
at Function.Module._load (node:internal/modules/cjs/loader:769:27)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:12)
at node:internal/main/run_main_module:17:47 {
code: 'MODULE_NOT_FOUND',
requireStack: []
}
This is the config file of my db
import mongoose from 'mongoose';
import colors from 'colors';
const connectDB = async () => {
try {
const conn = await mongoose.connect(process.env.MONGO_URI, {
useUnifiedTopology: true,
useNewUrlParser: true,
useCreateIndex: true,
});
console.log(`MongoDB Connected: ${conn.connection.host}`.cyan.underline);
} catch (error) {
console.error(`Error: ${error.message}`.red.underline.bold);
process.exit(1);
}
};
I tried to replace useCreateIndex: true, with useCreateIndexes: true, and It didnt work. I'm using mongoatlas. I read everything of my code and I cant find the error
import mongoose from 'mongoose';
import dotenv from 'dotenv';
import colors from 'colors';
import users from './data/users.js';
import products from './data/products.js';
import User from './models/userModel.js';
import Product from './models/productModel.js';
import Order from './models/orderModel.js';
import connectDB from './config/db.js';
dotenv.config();
connectDB();
const importData = async () => {
try {
await Order.deleteMany();
await Product.deleteMany();
await User.deleteMany();
const createdUsers = await User.insertMany(users);
const adminUser = createdUsers[0]._id;
const sampleProducts = products.map((product) => {
return { ...product, user: adminUser };
});
await Product.insertMany(sampleProducts);
console.log('Data Imported!'.green.inverse);
process.exit();
} catch (error) {
console.error(`${error}`.red.inverse);
process.exit(1);
}
};
const destroyData = async () => {
try {
await Order.deleteMany();
await Product.deleteMany();
await User.deleteMany();
console.log('Data Destroyed!'.red.inverse);
process.exit();
} catch (error) {
console.error(`${error}`.red.inverse);
process.exit(1);
}
};
if (process.argv[2] === '-d') {
destroyData();
} else {
importData();
}
this is the github repository of the tutorial https://github.com/bradtraversy/proshop_mern/blob/master/backend/config/db.js
Users need to specify the "isAdmin" field OR default value. Be sure that in './models/userModel.js' the isAdmin field look like this:
isAdmin: {
type: Boolean,
required: true,
default: false,
}
Related
I am using react and electron building an electron app.
I am new to react and electron and I got a problem on how to import a function in react index.js to electron main.js
Why I need to import that function to main.js file?
Because I need to pass the dependencies of my react app from main.js and most of these dependecies are function dependencies.
Here is the function in index.js which receive the dependencies. Look at the function dependency
mport React from 'react';
import ReactDOM from 'react-dom/client';
import './App.scss'
import './configFile'
import './fonts/NotoSansSC.otf'
import { init as initConfigFile } from './configFile'
import { init as initLanguage } from './international/language'
import App from './App';
export function dependency(config, saveConfigFile, createNewUser) {
}
const root = ReactDOM.createRoot(document.getElementById('root'))
initLanguage()
initConfigFile({
parentPwd: null,
qa: {
'configQuestion1': '123',
'configQuestion2': '123',
'configQuestion3': '123'
},
timeRangesNotAllowToUseTheComputer: [
],
language: 'en',
onlyWorkForTheUsers: ['test'],
usernames: ['onTheRoad', 'test'],
timeZones: { '中国': 'cn', '英国': 'uk' },
choosedTimeZone: 'uk'
}, null, null)
root.render(
<App />
)
Here is the main.js file
const path = require('path');
const { app, BrowserWindow } = require('electron');
const isDev = require('electron-is-dev');
function createWindow() {
// Create the browser window.
const win = new BrowserWindow({
width: 800,
height: 800,
webPreferences: {
nodeIntegration: true,
},
});
// and load the index.html of the app.
// win.loadFile("index.html");
win.loadURL(`file://${path.join(__dirname, '../build/index.html')}`);
// Open the DevTools.
if (isDev) {
win.webContents.openDevTools({ mode: 'detach' });
}
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(createWindow);
// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bars to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
I tried to import the file use require
const index = require('./index.js')
when I build the react app there is no error throwed but when I start the electron with electron . got error like this:
A JavaScript error occurred in the main process
Uncaught Exception:
/home/zxw/Desktop/bsd/src/index.js:1
import React from 'react';
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Object.compileFunction (node:vm:352:18)
at wrapSafe (node:internal/modules/cjs/loader:1040:15)
at Module._compile (node:internal/modules/cjs/loader:1076:27)
at Module._extensions..js (node:internal/modules/cjs/loader:1175:10)
at Module.load (node:internal/modules/cjs/loader:988:32)
at Module._load (node:internal/modules/cjs/loader:829:12)
at c._load (node:electron/js2c/asar_bundle:5:13339)
at Module.require (node:internal/modules/cjs/loader:1012:19)
at require (node:internal/modules/cjs/helpers:102:18)
at Object.<anonymous> (/home/zxw/Desktop/bsd/public/main.js:4:15)
libva error: vaGetDriverNameByIndex() failed with unknown libva error, driver_name = (null)
And then I tried to load the function by import statement like below
import {dependency} from '../src/index'
When I build react app there is no error throwed but when I start the electron app I got error like this
A JavaScript error occurred in the main process
Uncaught Exception:
/home/zxw/Desktop/bsd/public/main.js:4
import {dependency} from '../src/index'
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Object.compileFunction (node:vm:352:18)
at wrapSafe (node:internal/modules/cjs/loader:1040:15)
at Module._compile (node:internal/modules/cjs/loader:1076:27)
at Module._extensions..js (node:internal/modules/cjs/loader:1175:10)
at Module.load (node:internal/modules/cjs/loader:988:32)
at Module._load (node:internal/modules/cjs/loader:829:12)
at c._load (node:electron/js2c/asar_bundle:5:13339)
at loadApplicationPackage (/home/zxw/Desktop/bsd/node_modules/electron/dist/resources/default_app.asar/main.js:121:16)
at Object.<anonymous> (/home/zxw/Desktop/bsd/node_modules/electron/dist/resources/default_app.asar/main.js:233:9)
at Module._compile (node:internal/modules/cjs/loader:1120:14)
libva error: vaGetDriverNameByIndex() failed with unknown libva error, driver_name = (null)
Is there is a way to pass the dependencies to the index.js from main.js ?
I fix it by throgh a dump way
First install the axios and the express
Then in the react src file add a file called appDependency
Here is the code
import axios from 'axios'
export function saveConfigFile(config) {
try {
axios.put('http://localhost:8888/config', config).then(response => {
if (response.status !== 200) {
throw response.data
}
})
} catch (e) {
console.error(`Error occrred while saving the config file: ${e}`)
throw e
}
}
export function createNewUser(username, pwd) {
try {
axios.post('http://localhost:8888/users', {
username: username,
pwd: pwd
}).then((response) => {
if (response.status !== 200) {
throw response.data
}
})
} catch (e) {
console.error(`Error occrred while creating new user. ${e}`)
throw e
}
}
async function fetchTheConfig() {
return await axios.get('http://localhost:8888/config').then((response) => {
console.log(`The response is ${JSON.stringify(response.data)}`)
if (response.status !== 200) {
throw response.data
} else {
return response.data
}
})
}
export function getConfigFile() {
try {
return fetchTheConfig()
} catch (e) {
console.error(`err occurred while fetching the config file. ${e}`)
throw e
}
}
And in the electron main.js file I use express created a server
const path = require('path');
const { app, BrowserWindow } = require('electron');
const express = require('express')
const exApp = express()
exApp.use(express.urlencoded())
exApp.use(express.json())
const config = {
parentPwd: null,
qa: {
'configQuestion1': '123',
'configQuestion2': '123',
'configQuestion3': '123'
},
timeRangesNotAllowToUseTheComputer: [
],
language: 'en',
onlyWorkForTheUsers: ['test'],
usernames: ['onTheRoad', 'test'],
timeZones: { '中国': 'cn', '英国': 'uk' },
choosedTimeZone: 'uk'
}
function configFile(req, res) {
console.log(`request received getConfigFile`)
res.status(200).send(config)
}
function saveConfigFile(req, res) {
console.log(`The body is ${req.body.timeRangesNotAllowToUseTheComputer}`)
res.status(200).send()
}
function createNewUser(req, res) {
console.log(`The req is `)
}
function appDependecys() {
exApp.get('/config', configFile)
exApp.put('/config', saveConfigFile)
exApp.post('/users', createNewUser)
exApp.listen(8888)
}
appDependecys()
In the react index.js I made the change to
import React from 'react';
import ReactDOM from 'react-dom/client';
import './App.scss'
import './configFile'
import './fonts/NotoSansSC.otf'
import { init as initConfigFile } from './configFile'
import { init as initLanguage } from './international/language'
import App from './App';
import { getConfigFile, saveConfigFile, createNewUser } from './appDependency'
const root = ReactDOM.createRoot(document.getElementById('root'))
getConfigFile().then((cfg) => {
console.log(`The fucking config is ${cfg}`)
initLanguage()
initConfigFile(cfg, saveConfigFile, createNewUser)
root.render(
<App />
)
})
I'm trying to deploy a Next application with Prismic and i'm getting this error in the building process.
I have tried the solution with the webhook configuration in the Vercel servers without sucess Prismic Webhooks
Here is the [slug].tsx code:
export const getStaticPaths: GetStaticPaths = async () => {
return {
paths: [],
fallback: 'blocking'
}
}
export const getStaticProps: GetStaticProps = async ({ params }) => {
const prismic = getPrismicClient()
const { slug } = params;
const response = await prismic.getByUID('post', String(slug), {})
const post = {
slug,
title: RichText.asText(response.data.title),
content: RichText.asHtml(response.data.content),
updatedAt: new Date(response.last_publication_date).toLocaleDateString('pt-BR', {
day: '2-digit',
month: 'long',
year: 'numeric'
})
};
return {
props: {
post,
},
redirect: 60 * 60 * 24 * 7 //7 dias
}
}
This is the prismic.ts file:
import Prismic from '#prismicio/client'
export function getPrismicClient(req?: unknown) {
const prismic = Prismic.client(
process.env.PRISMIC_ENDPOINT,
{
req,
accessToken: process.env.PRISMIC_ACCESS_TOKEN
}
)
return prismic;
}
Here is the error log from Vercel:
22:13:41.009 Error occurred prerendering page "/posts". Read more: https://nextjs.org/docs/messages/prerender-error
22:13:41.009 TypeError: Only absolute URLs are supported
22:13:41.010 at getNodeRequestOptions (/vercel/path0/node_modules/node-fetch/lib/index.js:1305:9)
22:13:41.010 at /vercel/path0/node_modules/node-fetch/lib/index.js:1410:19
22:13:41.010 at new Promise (<anonymous>)
22:13:41.010 at fetch (/vercel/path0/node_modules/node-fetch/lib/index.js:1407:9)
22:13:41.011 at fetch (/vercel/path0/node_modules/cross-fetch/dist/node-ponyfill.js:10:20)
22:13:41.011 at fetchRequest (/vercel/path0/node_modules/#prismicio/client/cjs/#prismicio/client.js:989:24)
22:13:41.011 at DefaultRequestHandler.request (/vercel/path0/node_modules/#prismicio/client/cjs/#prismicio/client.js:1026:9)
22:13:41.011 at HttpClient.request (/vercel/path0/node_modules/#prismicio/client/cjs/#prismicio/client.js:1037:29)
22:13:41.011 at /vercel/path0/node_modules/#prismicio/client/cjs/#prismicio/client.js:1059:27
22:13:41.012 at DefaultApiCache.get (/vercel/path0/node_modules/#prismicio/client/cjs/#prismicio/client.js:956:19)
22:13:41.012 info - Generating static pages (3/7)
22:13:41.025 info - Generating static pages (5/7)
22:13:41.057 info - Generating static pages (7/7)
22:13:41.058 > Build error occurred
22:13:41.060 Error: Export encountered errors on following paths:
22:13:41.060 /posts
22:13:41.060 at /vercel/path0/node_modules/next/dist/export/index.js:31:1106
22:13:41.061 at runMicrotasks (<anonymous>)
22:13:41.061 at processTicksAndRejections (internal/process/task_queues.js:95:5)
22:13:41.062 at async Span.traceAsyncFn (/vercel/path0/node_modules/next/dist/telemetry/trace/trace.js:6:584)
22:13:41.062 at async /vercel/path0/node_modules/next/dist/build/index.js:43:49
22:13:41.062 at async Span.traceAsyncFn (/vercel/path0/node_modules/next/dist/telemetry/trace/trace.js:6:584)
22:13:41.062 at async /vercel/path0/node_modules/next/dist/build/index.js:25:1529
22:13:41.062 at async Span.traceAsyncFn (/vercel/path0/node_modules/next/dist/telemetry/trace/trace.js:6:584)
22:13:41.094 error Command failed with exit code 1.
22:13:41.094 info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
22:13:41.117 Error: Command "yarn run build" exited with 1
Attempting to run backend section of a project, and when I go to my localHost 5000 it says Server Is Ready, but when I try the path http://localhost:5000/api/users/ or http://localhost:5000/api/users/seed it says Cannot GET /api/users/. In my terminal, here's the code it throws.
[nodemon] starting `node --experimental-modules backend/server.js`
Serve at http://localhost:5000
(node:3612) UnhandledPromiseRejectionWarning: MongooseServerSelectionError: connect ECONNREFUSED
127.0.0.1:27017
at NativeConnection.Connection.openUri
(C:\Users\lumpy\Desktop\aaaaa\node_modules\mongoose\lib\connection.js:845:32)
at C:\Users\lumpy\Desktop\aaaaa\node_modules\mongoose\lib\index.js:345:10
at C:\Users\lumpy\Desktop\aaaaa\node_modules\mongoose\lib\helpers\promiseOrCallback.js:31:5
at new Promise (<anonymous>)
at promiseOrCallback (C:\Users\lumpy\Desktop\aaaaa\node_modules\mongoose\lib\helpers\promiseOrCallback.js:30:10)
at Mongoose._promiseOrCallback (C:\Users\lumpy\Desktop\aaaaa\node_modules\mongoose\lib\index.js:1135:10) at Mongoose.connect (C:\Users\lumpy\Desktop\aaaaa\node_modules\mongoose\lib\index.js:344:20)
at file:///C:/Users/lumpy/Desktop/aaaaa/backend/server.js:7:10
at ModuleJob.run (internal/modules/esm/module_job.js:152:23)
at async Loader.import (internal/modules/esm/loader.js:166:24)
at async Object.loadESM (internal/process/esm_loader.js:68:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:3612) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated
either by throwing inside of an async function without a catch block, or by rejecting a promise which
was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the
CLI flag `--unhandled-rejections=strict` (see
https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:3612) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future,
promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Both users and products are in the same folder, and while it can access and display the products fine, it cannot display the users. Before I noticed this, I was attempting to connect it to Mongo Compass, but it read "connect ECONNREFUSED 127.0.0.1:27017"
I never know what code to put up that's relevant, but here's the rest of my code.
userModel
import mongoose from 'mongoose';
const userSchema = new mongoose.Schema(
{
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
isAdmin: { type: Boolean, default: false, required: true }
},
{
timestamps: true,
}
);
const User = mongoose.model('User', userSchema);
export default User;
userRouter
import express from 'express';
import expressAsyncHandler from 'express-async-handler';
import data from '../data.js';
import User from '../models/userModel.js';
const userRouter = express.Router();
userRouter.get(
'/seed',
expressAsyncHandler(async (req, res) => {
const createdUsers = await User.insertMany(data.users);
res.send({ createdUsers });
})
);
export default userRouter;
server.js
import express from 'express';
import mongoose from 'mongoose';
import data from './data.js';
import userRouter from './routers/userRouter.js';
const app = express();
mongoose.connect(process.env.MONGODB_URL || 'mongodb://localhost/aaaaa', {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
});
app.get('/api/products/:id', (req, res) => {
const product = data.products.find((x) => x._id === req.params.id);
if (product) {
res.send(product);
} else {
res.status(404).send({ message: 'Product Not Found, gat dammit' });
}
});
app.get('/api/products', (req, res) => {
res.send(data.products);
});
app.use('/api/users', userRouter);
app.get('/', (req, res) => {
res.send('Server is ready');
});
app.use((err, req, res, next) => {
res.status(500).send({ message: err.message });
});
const port = process.env.PORT || 5000;
app.listen(port, () => {
console.log(`Serve at http://localhost:${port}`);
});
Mongoose connection is an async function, for which you need to use async await. try using:
(async() => {
await mongoose.connect(process.env.MONGODB_URL || 'mongodb://localhost/aaaaa', {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
});
})();
in your server.js file
In server.js after importing userRouter try adding
dotenv.config();
TLDR; I'm following an example from NextJS using Firebase, and with minimal change I can't push to Firebase.
I am following the NextJS with-firebase-hosting-and-typescript example, and in accordance with the help from #8893.
I changed the deploy script in package.json to cross-env NODE_ENV=production firebase deploy.
I also changed the conf value in functions/index.ts to
conf: {
distDir: `${path.relative(process.cwd(), __dirname)}/../functions/next`
}
When I go to deploy the app to firebase I now receive an error
Deployment error.
Error setting up the execution environment for your function. Please try deploying again after a few minutes.
I did some debugging and if I comment out the line
const app = next({ dev, conf: { distDir: `${path.relative(process.cwd(), __dirname)}/../functions/next` }
})
in functions/index.ts, then the functions will deploy just fine. So, the issue seems to be with next()
Here is code of the functions/index.ts, this throws the error.
import * as functions from 'firebase-functions'
import next from 'next'
import * as path from 'path'
const appSetup = {
dev: process.env.NODE_ENV !== 'production',
conf: { distDir: `${path.relative(process.cwd(), __dirname)}/../functions/next` }
}
console.log("appSetup: ", appSetup)
const app = next(appSetup)
// const handle = app.getRequestHandler()
export const nextApp = functions.https.onRequest(async(req, res) => {
// return app.prepare().then(() => handle(req, res))
return res.send({ status: "Hello from Firebase!, nextApp" })
})
Here is code of the functions/index.ts, this DOES NOT throw an error
import * as functions from 'firebase-functions'
import next from 'next'
import * as path from 'path'
const appSetup = {
dev: process.env.NODE_ENV !== 'production',
conf: { distDir: `${path.relative(process.cwd(), __dirname)}/../functions/next` }
}
console.log("appSetup: ", appSetup)
// const app = next(appSetup)
// const handle = app.getRequestHandler()
export const nextApp = functions.https.onRequest(async(req, res) => {
// return app.prepare().then(() => handle(req, res))
return res.send({ status: "Hello from Firebase!, nextApp" })
})
in package.json
"firebase-admin": "^8.10.0",
"firebase-functions": "^3.6.0",
"next": "^9.3.5",
"react": "16.13.1",
"react-dom": "16.13.1"
For anyone struggling with the same issue. The fix was the line in functions/index.ts
I needed to replace
conf: { distDir: `${path.relative(process.cwd(), __dirname)}/../functions/next` }
to
conf: { distDir: `${path.relative(process.cwd(), __dirname)}/next` }
I'm using this Amplify guide https://aws-amplify.github.io/docs/js/tutorials/building-react-native-apps/#connect-to-your-backend-1 and when I create an API using "aplify add api" the app fails.
I'm using "expo" and I'm using IphoneX for test phase.
My app code is
import React, { Component } from 'react';
import { StyleSheet, Text, Button, View, Alert } from 'react-native';
import Amplify, { API } from 'aws-amplify';
import amplify from './aws-exports';
import awsmobile from './aws-exports';
import { withAuthenticator } from 'aws-amplify-react-native';
Amplify.configure(amplify);
Amplify.configure(awsmobile);
state = { apiResponse: null };
class App extends Component {
async getSample() {
const path = "/items"; // you can specify the path
const apiResponse = await API.get("theListApi" , path); //replace the API name
console.log('response:' + apiResponse);
this.setState({ apiResponse });
}
render() {
return (
<View style={styles.container}>
<Text>test</Text>
<Button title="Send Request" onPress={this.getSample.bind(this)} />
<Text>Response: {this.state.apiResponse && JSON.stringify(this.state.apiResponse)}</Text>
</View>
);
}
}
export default withAuthenticator(App);
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#63C8F1',
alignItems: 'center',
justifyContent: 'center',
},
});
executing "expo start" the command line return this message error:
jest-haste-map: Haste module naming collision: theListFunction
The following files share their name; please adjust your hasteImpl:
* <rootDir>/amplify/backend/function/theListFunction/src/package.json
* <rootDir>/amplify/#current-cloud-backend/function/theListFunction/src/package.json
Failed to construct transformer: DuplicateError: Duplicated files or mocks. Please check the console for more info
at setModule (/Users/j_hen/Documents/jdev/smartApp/sourcecode/mySmaertProject/node_modules/jest-haste-map/build/index.js:620:17)
at workerReply (/Users/j_hen/Documents/jdev/smartApp/sourcecode/mySmaertProject/node_modules/jest-haste-map/build/index.js:691:9)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
at async Promise.all (index 391) {
mockPath1: 'amplify/backend/function/theListFunction/src/package.json',
mockPath2: 'amplify/#current-cloud-backend/function/theListFunction/src/package.json'
}
(node:1506) UnhandledPromiseRejectionWarning: Error: Duplicated files or mocks. Please check the console for more info
at setModule (/Users/j_hen/Documents/jdev/smartApp/sourcecode/mySmaertProject/node_modules/jest-haste-map/build/index.js:620:17)
at workerReply (/Users/j_hen/Documents/jdev/smartApp/sourcecode/mySmaertProject/node_modules/jest-haste-map/build/index.js:691:9)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
at async Promise.all (index 391)
(node:1506) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:1506) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
or
Error: Duplicated files or mocks. Please check the console for more info
at setModule (/Users/j_hen/Documents/jdev/smartApp/sourcecode/mySmaertProject/node_modules/jest-haste-map/build/index.js:620:17)
at workerReply (/Users/j_hen/Documents/jdev/smartApp/sourcecode/mySmaertProject/node_modules/jest-haste-map/build/index.js:691:9)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
at async Promise.all (index 391)
What is wrong? How can I use the API correctly?
Amplify creates a copy of your current cloud backend configuration in amplify/#current-cloud-backend/.
You don't need those files to build your app, so you can ignore them in order to get rid of the error.
To do so, you can create a blacklist and add the folder to it.
Create a rn-cli.config.js file in the root of your project.
./rn-cli.config.js:
// works with older react native versions
// const blacklist = require('metro').createBlacklist;
const blacklist = require('metro-config/src/defaults/blacklist');
module.exports = {
resolver: {
blacklistRE: blacklist([/#current-cloud-backend\/.*/]),
},
};
Reference issue.
TypeScript considerations:
(As stated in Mush's answer)
If you are using typescript you should create the blacklist on
metro.config.js NOT rn-cli.config.js.
module.exports = {
resolver: {
blacklistRE: /#current-cloud-backend\/.*/
},
transformer: {
getTransformOptions: async () => ({
transform: {
experimentalImportSupport: false,
inlineRequires: false,
},
}),
},
};
As stated
here.
2022
In Metro v0.64.0 blacklist was renamed to blocklist, release notes
My current solution is to edit the metro.config.js (or create a new one) and add the following
const exclusionList = require('metro-config/src/defaults/exclusionList');
module.exports = {
resolver: {
blacklistRE: exclusionList([/amplify\/#current-cloud-backend\/.*/]),
},
transformer: {
getTransformOptions: async () => ({
transform: {
experimentalImportSupport: false,
inlineRequires: false,
},
}),
},
};
If you are using typescript you should create the blacklist on metro.config.js NOT rn-cli.config.js.
module.exports = {
resolver: {
blacklistRE: /#current-cloud-backend\/.*/
},
transformer: {
getTransformOptions: async () => ({
transform: {
experimentalImportSupport: false,
inlineRequires: false,
},
}),
},
};
As stated here.
I just ran into this problem and had to create ./rn-cli.config.js with the following as blacklist was in a different folder:
const blacklist = require('metro-config/src/defaults/blacklist');
module.exports = {
resolver: {
blacklistRE: blacklist([/#current-cloud-backend\/.*/]),
},
};
After updating to Expo SDK41 this issue came back.
I needed to change previous rn-cli.config.js to metro.config.js (even though I'm not using TS) and install #expo/metro-config as devDependency.
Expo + Late 2021 Update
Not sure if this is fix is expo specific, but the current way to do this is with blacklist (rather than exclusionList). Like so:
metro.config.js
const blacklist = require("metro-config/src/defaults/blacklist")
module.exports = {
resolver: {
blacklistRE: blacklist([/amplify\/#current-cloud-backend\/.*/]),
},
transformer: {
getTransformOptions: async () => ({
transform: {
experimentalImportSupport: false,
inlineRequires: false,
},
}),
},
}
For anyone who is still facing this issue I had to change something after this issue re-appeared.
For me, I had to change blacklist in line 1 to exclusionList
metro.config.js
const blacklist = require("metro-config/src/defaults/exclusionList")
module.exports = {
resolver: {
blacklistRE: blacklist([/amplify\/#current-cloud-backend\/.*/]),
},
transformer: {
getTransformOptions: async () => ({
transform: {
experimentalImportSupport: false,
inlineRequires: false,
},
}),
},
}