I am creating react product using gatsby. I am using react-pdf library. It is givining follwoing error at build time. How can I solve it?
I used gatsby 3.3.0 version.
and using react-pdf 5.2.0
D:\Project\public\render-page.js:137661
window.requestAnimationFrame(resolve);
ReferenceError: window is not defined
at D:\Project\public\render-page.js:40343:3
at new Promise (<anonymous>)
at Object../node_modules/pdfjs-dist/lib/web/ui_utils.js (D:\Project\public\render-page.js:4034
2:26)
at __webpack_require__ (D:\Project\public\render-page.js:48664:42)
at Object../node_modules/pdfjs-dist/lib/web/pdf_link_service.js (D:\Brisktech\Android\public\render-page
.js:39345:17)
at __webpack_require__ (D:\Project\public\render-page.js:48664:42)
at Module../node_modules/react-pdf/dist/esm/LinkService.js (D:\Project\public\render-page.js:4
4080:93)
at __webpack_require__ (D:\Project\public\render-page.js:48664:42)
at Module../node_modules/react-pdf/dist/esm/Document.js (D:\Project\public\render-page.js:4351
2:71)
at __webpack_require__ (D:\Project\public\render-page.js:48664:42)
at Module../node_modules/react-pdf/dist/esm/entry.webpack.js (D:\Brisktech\Android\public\render-page.js
:46550:67)
at __webpack_require__ (D:\Project\public\render-page.js:48664:42)
at Module../src/routes/default/index.js (D:\Project\public\render-page.js:7404:90)
at __webpack_require__ (D:\Project\public\render-page.js:48664:42)
at Object../.cache/_this_is_virtual_fs_path_/$virtual/sync-requires.js (D:\Brisktech\Android\public\rend
er-page.js:6740:116)
at __webpack_require__ (D:\Project\public\render-page.js:48664:42)
D:\Project\public\render-page.js:40343
window.requestAnimationFrame(resolve);
^
failed Building static HTML for pages - 2.931s
ERROR #95313
Building static HTML failed
See our docs page for more info on this error: https://gatsby.dev/debug-html
10 |
11 | export default function _createClass(Constructor, protoProps, staticProps) {
> 12 | if (protoProps) _defineProperties(Constructor.prototype, protoProps);
| ^
13 | if (staticProps) _defineProperties(Constructor, staticProps);
14 | return Constructor;
15 | }
WebpackError: Call retries were exceeded
- createClass.js:12
[fitupme-app]/[#babel]/runtime/helpers/esm/createClass.js:12:1
error Command failed with exit code 1.
If I lower the version of react-pdf then It is working but giving warning.
react-pdf: 4.2.0
ERROR
(node:6076) [DEP_WEBPACK_COMPILATION_CACHE] DeprecationWarning: Compilation.cache was removed in favor of
Compilation.getCache()
(Use `node --trace-deprecation ...` to show where the warning was created)
ERROR
(node:6076) [DEP_WEBPACK_TEMPLATE_PATH_PLUGIN_REPLACE_PATH_VARIABLES_HASH] DeprecationWarning: [hash] is now
[fullhash] (also consider using [chunkhash] or [contenthash], see documentation for details)
ERROR
(node:6076) [DEP_WEBPACK_DEPRECATION_ARRAY_TO_SET_INDEXER] DeprecationWarning: chunk.files was changed from Array to Set (in
dexing Array is deprecated)
Can Anyone solve this?
As the error prompts in:
See our docs page for more info on this error:
https://gatsby.dev/debug-html
Your issue relies on the fact that gatsby develop occurs in the browser (where there are window and other global objects while gatsby build occurs in the Node server, where for obvious reasons there is no window (summarizing a lot).
When dealing with own code, you can bypass this issue wrapping your logic in the following condition:
import * as React from "react"
// Check if window is defined (so if in the browser or in node.js).
const isBrowser = typeof window !== "undefined"
export default function MyComponent() {
let loggedIn = false
if (isBrowser) {
window.localstorage.getItem("isLoggedIn") === "true"
}
return <div>Am I logged in? {loggedIn}</div>
}
Source: https://www.gatsbyjs.com/docs/debugging-html-builds/
The snippet above will avoid a breaking build because it won't execute the offending part of the code thanks to typeof window !== "undefined" condition.
However, in your case, you are not dealing with own code so you need to tell webpack to avoid the transpilation of the offending modules. Add the following snippet in your gatsby-node.js:
exports.onCreateWebpackConfig = ({ stage, loaders, actions }) => {
if (stage === "build-html" || stage === "develop-html") {
actions.setWebpackConfig({
module: {
rules: [
{
test: /bad-module/,
use: loaders.null(),
},
],
},
})
}
}
Basically, you are overwriting webpack's default configuration by telling it to ignore (or to add a null loader) to the /bad-module/ dependency. As you can see, the test rule is a regular expression (that's why is wrapped between slashes) so you will need to change /bad-module/ for the name of the dependency in node_modules. Something like this should work:
exports.onCreateWebpackConfig = ({ stage, loaders, actions }) => {
if (stage === "build-html" || stage === "develop-html") {
actions.setWebpackConfig({
module: {
rules: [
{
test: /react-pdf/, // check /pdfjs-dist/ too
use: loaders.null(),
},
],
},
})
}
}
react-pdf is trying to use window and/or document, what are undefined global objects at build-time to make their stuff so you are forced to pass a null loader to avoid the code-breaking. This is a "common" practice when dealing with third-party dependencies that use window in Gatsby.
Since it may not be exactly the third-party dependency that is causing the issue (it may be some dependency of react-pdf) you will need to make some trials testing dependencies based on the output log. Clean the cache in each trial using gatsby clean command.
Related
So I couldn't build my gatsby app because it has quite a lot of dependencies on window. Many components are built depending on the width of the browser window.
After the "gatsby build" command I got WebpackError: ReferenceError: window is not defined.
I found a solution on the internet to paste the following code into gatsby-node.js:
exports.onCreateWebpackConfig = ({ stage, loaders, actions }) => {
if (stage === 'build-html' || stage === 'develop-html') {
actions.setWebpackConfig({
module: {
rules: [
{
test: /node_modules/,
use: loaders.null(),
},
],
},
});
}
};
but when rebuilding the app I get this error:
<w> [webpack.cache.PackFileCacheStrategy] Skipped not serializable cache item 'Compilation/modules|json|C:\Users\Damian\Documents\Ossolinsky\app\node_modules\null-loader\dist\cjs.js??ruleSet[1].rules[13].use!C:\Users\Damian\Documents\Ossolinsky\app\node_modules\gatsby\package.json': No serializer registered for JSONParseError
ERROR #98123 WEBPACK
Generating SSR bundle failed
Unexpected end of JSON input while parsing empty string
File: node_modules\gatsby\package.json
not finished Building HTML renderer - 1.257s
I found a solution on the internet to paste the following code into
gatsby-node.js
This is the recipe of the devil. With the following snippet:
{
test: /node_modules/,
use: loaders.null(),
},
You are adding a null loader to all node_modules folder and the idea here is to add only instances that need to be ignored in the server because they had a window dependency. Since rules is an array you can do:
exports.onCreateWebpackConfig = ({ stage, loaders, actions }) => {
if (stage === 'build-html' || stage === 'develop-html') {
actions.setWebpackConfig({
module: {
rules: [
{
test: /some_package_1/,
use: loaders.null(),
},
{
test: /some_package_2/,
use: loaders.null(),
},
{
test: /some_package_3/,
use: loaders.null(),
},
],
},
});
}
};
Keep in mind that /some_package_3/ is a regular expression (hence the test key and that's why is between slashes) that needs to match the folder name inside node_modules.
To know which string should be placed as a regular expression, normally if you import { some_package_1 } from 'some_package_1' means that some_package_1 is the folder inside node_modules that needs to be added.
There's a chance that some_package_1 is not using a window per se, and it's a dependency of the dependency: in that case, you need to find out which one is it and apply the same reasoning ignoring it.
Many components are built depending on the width of the browser
window.
If those are internal components, you should check first if there's a window available when the component is being rendered/parsed, as the docs suggests, with the following condition:
export default function MyComponent() {
if (typeof window !== "undefined") {
return <div>Component that can use window and will bypass SSR</div>
}
return <div>Component that can't use window</div>
}
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
Hi I actually need to import exported files from one application(commons) to other application(login) in some jest files, but it is not getting detected by jest.
Jest Test file:
import { auth as ServiceAuth } from "#dfs/standard"
import { ContextAlert } from '#dfs/standard';
describe("login page", () => {
it("test case 1", () => {
const ContextAlert = useContext(ContextAlert );
expect(ContextAlert).toBeTruthy()
})
})
Error Message:
FAIL src/Components/LoginPage.test.js
● Test suite failed to run
Cannot find module '#dfs/standard' from 'LoginPage.test.js'
> 1 | import { auth as ServiceAuth } from "#dfs/standard"
| ^
2 | import { ContextAlert } from '#dfs/standard';
3 |
4 | describe("login page", () => {
at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:299:11)
at Object.<anonymous> (src/Components/LoginPage.test.js:1:1)
jest.config.js
module.exports = {
transform: {
"^.+\\.(j|t)sx?$": "babel-jest"
},
moduleNameMapper: {
"\\.(css)$": "identity-obj-proxy",
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "identity-
obj-proxy",
}
};
But the file is getting imported in the component files with the same syntax.
How can I import the file in the jest test file ?
Jest is a very different environment than the browser, and resolving modules is also different. The code being loaded in Jest is not bundled and has not been processed through Webpack so externals are not resolved at run-time.
To enable unit tests with cross microfrontend imports, these are your options:
Publish mocks for that shared dependency (so that the mock and the actual implementation are nearest to each other)
Mock the shared dependency with Jest’s moduleNameMapper configuration
Mock the shared dependency locally in a __mocks__ file
Publish the shared dependency to a registry (npm or some other internal registry such as artifactory) and install it as a devDependency locally so that Jest can resolve it locally (though this will likely require a separate build to execute in jest/node environment)
The option you choose depends on your organization's needs.
See also: https://github.com/single-spa/single-spa.js.org/issues/389
I am creating a new react app with gatsby, typescript, and apollo (for graphql queries).
When testing in dev, the app compiles and runs with no errors thrown.
When I transpile the build, using 'gatsby build', it fails with an error.
I don't understand why or where this is being triggered. It seems to be something to do with the way webpack is checking as it's building, but I don't know how to pinpoint the issue and there doesn't seem to be any material out there with a clear answer for me.
It seems to be caused by the httplink module. The code that triggers the error when present in any .tsx file is:
import { HttpLink } from 'apollo-link-http'
const link = new HttpLink({
uri: 'http://localhost:3001/graphql'
})
The error shown is the following:
error Building static HTML failed
See our docs page on debugging HTML builds for help https://gatsby.dev/debug-html
10 | function InvariantError(message) {
11 | if (message === void 0) { message = genericMessage; }
> 12 | var _this = _super.call(this, typeof message === "number"
| ^
13 | ? genericMessage + ": " + message + " (see https://github.com/apollographql/invariant-packages)"
14 | : message) || this;
15 | _this.framesToPop = 1;
WebpackError: Invariant Violation: Invariant Violation: 1 (see https://github.com/apollographql/invariant-packages)
- invariant.esm.js:12 new InvariantError
[lib]/[apollo-link-http-common]/[ts-invariant]/lib/invariant.esm.js:12:1
- bundle.esm.js:64 checkFetcher
[lib]/[apollo-link-http-common]/lib/bundle.esm.js:64:52
- bundle.esm.js:8 createHttpLink
[lib]/[apollo-link-http]/lib/bundle.esm.js:8:17
- bundle.esm.js:139 new HttpLink
[lib]/[apollo-link-http]/lib/bundle.esm.js:139:1
- Strategy.tsx:6 Module../src/components/Strategy.tsx
lib/src/components/Strategy.tsx:6:14
- bootstrap:19 __webpack_require__
lib/webpack/bootstrap:19:1
- bootstrap:19 __webpack_require__
lib/webpack/bootstrap:19:1
- sync-requires.js:10 Object../.cache/sync-requires.js
lib/.cache/sync-requires.js:10:56
- bootstrap:19 __webpack_require__
lib/webpack/bootstrap:19:1
- static-entry.js:9 Module../.cache/static-entry.js
lib/.cache/static-entry.js:9:22
- bootstrap:19 __webpack_require__
lib/webpack/bootstrap:19:1
- bootstrap:83
lib/webpack/bootstrap:83:1
- universalModuleDefinition:3 webpackUniversalModuleDefinition
lib/webpack/universalModuleDefinition:3:1
- universalModuleDefinition:10 Object.<anonymous>
lib/webpack/universalModuleDefinition:10:2"
Is this typescript issue, gatsby issue, apollo issue, or a webpack issue? Or a combination?
Thank you for any help you can give! I'm struggling with my understanding of all the pieces here.
I understand that Invariant Violations are about an issue with the wrong types being referenced. Because this occurs in the module, I'm not sure if I'm doing something wrong, or if it's an issue inside the imported library. Maybe it's an issue that I'm forcing typescript checks on a basic javascript based library. I still didn't quite come to a conclusion on this.
I tried adding the following config to gatsby-node.js to ignore the module checks (as suggested here: https://gatsby.dev/debug-html), with no successful build, though the error did change, as it could not see the module.
exports.onCreateWebpackConfig = ({ stage, loaders, actions }) => {
if (stage === "build-html") {
actions.setWebpackConfig({
module: {
rules: [
{
test: /apollo-link-http/,
use: loaders.null(),
},
],
},
})
}
}
To recap, this is the code designed to create the client object to enable queries to the graphql endpoint. When running 'gatsby build' the in variant error occurs (see above).
import * as React from 'react'
import { ApolloClient } from 'apollo-client'
import { InMemoryCache } from 'apollo-cache-inmemory'
import { HttpLink } from 'apollo-link-http'
const cache = new InMemoryCache()
const link = new HttpLink({
uri: 'http://localhost:3001/graphql'
})
const client = new ApolloClient({
cache,
link
})
I'm a newbie at this. After hours of looking I finally tracked down the error in the file. On closer inspection, when the environment is production (process.env.NODE_ENV === "production"), then the error is not detailed. So I looked at what the error would be if the environment was something else, and changed the file to output this to the console. What I got back was:
fetch is not found globally and no fetcher passed, to fix pass a fetch for
your environment like https://www.npmjs.com/package/node-fetch.
For example:
import fetch from 'node-fetch';
import { createHttpLink } from 'apollo-link-http';
const link = createHttpLink({ uri: '/graphql', fetch: fetch });
I added fetch to my code, and it built a production version with no errors.
I don't understand why this error was not thrown with the dev environment, but I guess it's something to do with the lazy loading.
Problem fixed.
I want to test the alert message in detox,and the message use i18n.
const i18n = require("react-native-i18n");
describe("Example", () => {
beforeEach(async () => {
await device.reloadReactNative();
});
it("should show hello screen after tap", async () => {
await element(by.id("btnLogin")).tap();
I18n.t(LocaleKeys.errorMsg_invalidUsername);
await expect(element(by.text(I18n.t(LocaleKeys.errorMsg_invalidUsername)))).toBeVisible();
// await expect(element(by.text("Please input the email and password."))).toBeVisible();
});
});
Run test and get the following error.
Test suite failed to run
/Users/leogeng/Desktop/studentREP/student-app/node_modules/react-native-i18n/index.js:14
export const getLanguages = () => RNI18n.getLanguages();
^^^^^^
SyntaxError: Unexpected token export
at ScriptTransformer._transformAndBuildScript (../node_modules/jest-runtime/build/script_transformer.js:305:17)
at Object.<anonymous> (firstTest.spec.js:1:114)
at Generator.next (<anonymous>)
Then I add the following code for jest:
{
"preset": "react-native",
"transformIgnorePatterns": [
"/node_modules/(?!(react-native(.*)?/|native-base(.*)?/|react-navigation/))"
]
}
and get error again:
Validation Error:
Module <rootDir>/node_modules/react-native/jest/setup.js in the setupFiles option was not found.
Actually i confirm 'setup,js' exist in node_modules/react-native/jest.
I do not know why the error happens, anybody can help me?
Thanks
Most likely it's because you're using an old version of node, try to update and see if it solves the issue. Also, it's completely unrelated to Jest and you should probably revert your attempts to modify Jest settings if you don't have any issues with Jest unit tests; in anyway, it will not fix the detox issues.
In case you have some requirement or reason which forces you to keep node at a specific old version, you can bypass it by performing the test differently: have a demo screen only for the e2e tests (or even create a whole demo project just for e2e), in the demo screen you can have a button which performs what you need with i18n (changing locale or whatever), and in the detox test you tap this "demo" button before testing what you actually want.
I've had the same problem. I resolve it by importing i18n-js instead of react-native-i18n.
Because react-native-i18n is not a plain javascript framework, Detox can't import it.
But react-native-i18n is using i18n-js, so you can access your translations without any problem
const I18n = require('i18n-js')
// and then you can use it for your tests
...
await element(by.text( I18n.t('hello') )).tap()