I am trying to use Playfab SDK on my React project, but no success yet..
I can't find well explained documentation for it.
created a react app with:
npx create-react-app playfabtest
installing PlayFab SDK for nodejs:
npm install playfab-sdk
NOTE: ( there is another SDK for JavaScript (npm install playfab-web-sdk), but I am assuming that for a react app, the nodes is the correct one ?)
The documentation for those SDK
Modified the App.js file on the project with this code:
(tried in many ways actually, I put the last one tried that didn't work neither).
App.js:
// import { PlayFabClient } from './playfab-sdk/Scripts/PlayFab/PlayFabClient';
// var PlayFabClient = require('./PlayFabSdk/Scripts/PlayFab/PlayFabClient.js')
function App() {
const PlayFabClient = require('./PlayFabSdk/Scripts/PlayFab/PlayFabClient.js');
PlayFabClient.settings.titleId = '';
PlayFabClient.settings.developerSecretKey = '';
PlayFabClient.GetTitleData({ Keys: ['Sample'] }, function (error, result) {
if (error) {
console.log('Got an error: ', error);
return;
}
console.log('Reply: ', result);
});
return ...
}
After that, if I run : npm start
get this error :
error:
Compiled with problems:
ERROR in ./src/PlayFabSdk/Scripts/PlayFab/PlayFab.js 4:10-24
Module not found: Error: Can't resolve 'url' in 'D:\Github\playfabtest\src\PlayFabSdk\Scripts\PlayFab'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default. This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "url": require.resolve("url/") }'
- install 'url' If you don't want to include a polyfill, you can use an empty module like this: resolve.fallback: { "url": false }
ERROR in ./src/PlayFabSdk/Scripts/PlayFab/PlayFab.js 6:12-28
Module not found: Error: Can't resolve 'https' in 'D:\Github\playfabtest\src\PlayFabSdk\Scripts\PlayFab'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default. This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "https": require.resolve("https-browserify") }'
- install 'https-browserify' If you don't want to include a polyfill, you can use an empty module like this: resolve.fallback: { "https": false }
Would be very helpful if can explain how to make PlayfabSDK run well on a react app.
Thanks a lot!
In the context of Create React App, you need to use ES6 style import statement instead of require to import the playfab-sdk NPM package into your project. Also you need to set the settings on the PlayFab object instead of the PlayFabClient.
Example:
import { useEffect, useState } from 'react';
import { PlayFab, PlayFabClient } from 'playfab-sdk'
PlayFab.settings.titleId = process.env.REACT_APP_PLAYFAB_TITLE_ID || ''
PlayFab.settings.developerSecretKey = process.env.REACT_APP_PLAYFAB_DEVELOPER_SECRET_KEY
// continue with component implementation
const App {
// get title data
PlayFabClient.GetTitleData(...)
// etc...
}
export default App
Related
When I want to verify the jwt token in React with TypeScript, it gives this error, how to solve it?
`
const [decodedToken, setDecodedToken] = useState<null | JwtPayload | string>(null);
const verifyToken = (token: string) => {
try {
// Decode the token
const decoded = jwt.verify(token, `${process.env.REACT_APP_JWT_SECRET}`);
// Check if the token is valid
if (decoded) {
return decoded;
}
} catch (err) {
// Return null if the token is invalid
return null;
}
};
useEffect(() => {
const localToken = localStorage.getItem(
`${process.env.REACT_APP_APPLICATION_NAME}-auth`
);
if (localToken) {
const token = JSON.parse(localToken);
const decoded = verifyToken(token.token);
if (decoded) {
// The token is valid, set the decoded token in state
setDecodedToken(decoded);
} else {
// The token is invalid, redirect the user to the login page
}
}
}, []);
`
Compiled with problems:X
ERROR in ./node_modules/buffer-equal-constant-time/index.js 4:13-37
Module not found: Error: Can't resolve 'buffer' in '/home/hossain/Documents/projects/travel-hunter/client/node_modules/buffer-equal-constant-time'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
add a fallback 'resolve.fallback: { "buffer": require.resolve("buffer/") }'
install 'buffer'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "buffer": false }
ERROR in ./node_modules/jsonwebtoken/sign.js 18:4-21
Module not found: Error: Can't resolve 'crypto' in '/home/hossain/Documents/projects/travel-hunter/client/node_modules/jsonwebtoken'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
add a fallback 'resolve.fallback: { "crypto": require.resolve("crypto-browserify") }'
install 'crypto-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "crypto": false }
I have tried many solutions in github, stackoverflow, but can't solve it!
Unfortunately, I do not think you are able to solve this problem with the 'jsonwebtoken' package. However, you can verify your token using a package called jwt_decode. You can begin by decoding your token, then logging it into the console.
import jwt_decode from "jwt-decode";
const decoded = jwt_decode(token)
console.log(decoded)
You will then know the type of data being received when the token is verified. You can then use this to create a helper function to serialize the data to the desired format.
export function deleteProps (obj: unserializedData, props: string[]) {
for (var i = 0; i < props.length; i++) {
if (obj.hasOwnProperty(props[i])) {
// #ts-ignore
delete obj[props[i]];
}
}
return obj
}
The object return will now be of the required data type and you will be able to update your react state.
const serializedUser = deleteProps(decoded, ['_v','exp','iat'])
setDecodedToken(serializedUser)
For more information on the topic you can check this question here
I'm trying to load #apollo/client on a React Native Expo app.
And I get this error:
While trying to resolve module #apollo/client from file /Users/andrepena/git/anglio-mobile-rn/screens/dictionary/index.tsx, the package /Users/andrepena/git/anglio-mobile-rn/node_modules/#apollo/client/package.json was successfully found. However, this package itself specifies a main module field that could not be resolved (/Users/andrepena/git/anglio-mobile-rn/node_modules/#apollo/client/main.cjs. Indeed, none of these files exist
Then I searched Stackoverflow and someone said I should add this to my metro.config.json
const { getDefaultConfig } = require("#expo/metro-config");
const defaultConfig = getDefaultConfig(__dirname);
defaultConfig.resolver.assetExts.push("cjs");
module.exports = defaultConfig;
But now, all imports from #apollo/client simply return undefined.
Example:
import { ApolloClient, InMemoryCache } from "#apollo/client";
console.log(ApolloClient); // undefined
console.log(InMemoryCache); // undefined
In fact, #apollo/client is exporting this object:
Object {
"default": 17,
}
Any suggestion?
This metro.config.js worked for me: (remember to install #expo/metro-config)
const { getDefaultConfig } = require('#expo/metro-config');
const config = getDefaultConfig(__dirname, {
// Initialize in exotic mode.
// If you want to preserve `react-native` resolver main field, and omit cjs support, then leave this undefined
// and skip setting the `EXPO_USE_EXOTIC` environment variable.
mode: 'exotic',
});
module.exports = config;
The exotic thing makes Metro to be able to find the weird cjs module that #apollo/client exports
I have a new package to add to my build for a React SPA. I'm using package.json, webpack 3.x and npm. The instructions for the package are:
To use the library locally without publishing to a remote npm registry, first install the dependencies by changing
into the directory containing `package.json` (and this README). Let's call this `JAVASCRIPT_CLIENT_DIR`. Then run:
shell
npm install
Next, [link](https://docs.npmjs.com/cli/link) it globally in npm with the following, also from `JAVASCRIPT_CLIENT_DIR`:
shell
npm link
Finally, switch to the directory you want to use your nba_v3_headshots from, and run:
shell
npm link /path/to/<JAVASCRIPT_CLIENT_DIR>
You should now be able to `require('nba_v3_headshots')` in javascript files from the directory you ran the last
command above from.
When I follow the instructions, I get errors during my production build or development build like this one:
ERROR in ./app/components/FooterView/vendor/javascript-client/src/index.js
Module not found: Error: Can't resolve 'ApiClient' in '/Users/{builddir}/app/components/FooterView/vendor/javascript-client/src'
In my code I'm loading the package like this:
import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
var NbaV3Headshots = require('nba_v3_headshots');
In the package's src/index.js
./app/components/FooterView/vendor/javascript-client/src/index.js I have:
(function(factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['ApiClient', 'model/Headshot', 'api/DefaultApi'], factory);
} else if (typeof module === 'object' && module.exports) {
// CommonJS-like environments that support module.exports, like Node.
module.exports = factory(require('./ApiClient'), require('./model/Headshot'), require('./api/DefaultApi'));
}
}(function(ApiClient, Headshot, DefaultApi) {
'use strict';
var exports = {
/**
* The ApiClient constructor.
* #property {module:ApiClient}
*/
ApiClient: ApiClient,
/**
* The Headshot model constructor.
* #property {module:model/Headshot}
*/
Headshot: Headshot,
/**
* The DefaultApi service constructor.
* #property {module:api/DefaultApi}
*/
DefaultApi: DefaultApi
};
return exports;
}));
npm ls -g show my package like this:
nba_v3_headshots#1.0.0 -> /Users/{builddir}/app/components/FooterView/vendor/javascript-client
The package is not listed in package.json.
Is there another way to add the package, or to fix the require() ?
If anyone else hits this, I had to use a regular import statement instead of require.
import {ApiClient, Headshot, DefaultApi} from './vendor/javascript-client';
I also had to turn off parsing of amd in my config/webpack.config.js like this:
const commonRules = [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
parser: {
amd:false, <---------- here
},
query: {
because our build has both UMD and AMD imports.
I am trying to migrate a CRA react application to NX, following steps on the official site
When I hit nx serve
I am facing the following error:
ERROR in C:/dev/nx-dev/scandy/node_modules/#react-pdf/png-js/dist/png-js.browser.es.js
Module not found: Error: Can't resolve 'zlib' in 'C:\dev\nx-dev\scandy\node_modules#react-pdf\png-js\dist'
ERROR in C:/dev/nx-dev/scandy/node_modules/#react-pdf/pdfkit/dist/pdfkit.browser.es.js
Module not found: Error: Can't resolve 'zlib' in 'C:\dev\nx-dev\scandy\node_modules#react-pdf\pdfkit\dist'
Knowing that: before I start migration my project worked fine.
npm version: 6.14.11
node version: 14.16.0
I've tried to hit npm install zlib yet I get
Cannot find module './zlib_bindings'
For some reason, VSCode inserted import e from 'express' at the top of my file in react
import { response } from 'express';
I delete the above import line and then the problem is resolved, all the errors are gone after the above change.
It's about Webpack 5 and its default config you use for React app. I followed an advice from here: https://github.com/nrwl/nx/issues/4817#issuecomment-824316899 and React NX docs for how to use custom webpack config.
Create a custom webpack config, say, in /apps/myapp/webpack.config.js and reference it in workspace.json instead of "webpackConfig": "#nrwl/react/plugins/webpack". It should be "webpackConfig": "apps/myapp/webpack.config.js".
Content for webpack.config.js:
const nrwlConfig = require("#nrwl/react/plugins/webpack.js");
module.exports = (config, context) => {
// first call it so that #nrwl/react plugin adds its configs
nrwlConfig(config);
return {
...config,
node: undefined
};
};
So, this config change makes webpack correctly understand what polyfills are needed.
Alternatively, you can do the following:
const nrwlConfig = require("#nrwl/react/plugins/webpack.js");
module.exports = (config, context) => {
// first call it so that #nrwl/react plugin adds its configs
nrwlConfig(config);
return {
...config,
resolve: {
...config.resolve,
alias: {
...config.resolve.alias,
stream: require.resolve('stream-browserify'),
zlib: require.resolve('browserify-zlib'),
}
}
};
};
For me it was the code:
import { response } from 'express'
This was entered automatically by VSCode at the beginning of the file.
Deleting it solved the problem.
In my case was because I tried to type 'Text' and suddenly, the autocomplete added me this line on top:
import { text } from 'express';
Just deleted it and it worked fine.
Go Search Icon in VSCode search "express" you may get things like
import { text } from 'express'
import { Router } from 'express'
import { X,Y,Z } from 'express'
delete this line your app will work fine
I am trying to use superagent with the create-react-app bootstrapper. I get the error:
Error in ./src/ToDoApp.js
Module not found: [CaseSensitivePathsPlugin] node_modules\superagent\lib\client.js does not match the corresponding path on disk - File does not exist.
I am importing the modules:
import request from 'superagent';
import noCache from 'superagent-no-cache';
I am using my request.get in ComponentDidMount
componentDidMount(){
request.get(this.apiUrl)
.use(noCache)
.end(function _requestCallback() {
// this.setState({data:res.data});
console.log('gotit');
});
}
Any ideas?
Edit:
An idea: install a newer version of both modules and try again