ReferenceError: $RefreshReg$ is not defined - reactjs

In a CRA based React app I get this error in a webworker file (all code is using Typescript) when I import files that are also imported by normal application code (normal === non-worker) and run the app using the babel dev server in debug mode.
Searching for this error brings me to various module specific issue reports/solutions, which I cannot use, however. But it's clear that this is a React hot reloading problem and I wonder how to solve it, as it keeps me from using my app code also in web workers.
My dev dependencies are:
"devDependencies": {
"#babel/core": "^7.12.10",
"#babel/preset-env": "^7.11.11",
"#babel/preset-typescript": "^7.12.7",
"#testing-library/react": "^11.2.3",
"#types/classnames": "^2.2.11",
"#types/color": "^3.0.1",
"#types/d3": "^6.2.0",
"#types/history": "4.7.8",
"#types/jest": "^26.0.20",
"#types/lodash": "^4.14.168",
"#types/node": "^14.14.22",
"#types/react": "^17.0.0",
"#types/react-dom": "^17.0.0",
"#types/react-test-renderer": "^17.0.0",
"#types/react-window": "^1.8.2",
"#types/resize-observer-browser": "^0.1.5",
"#types/selenium-webdriver": "^4.0.11",
"#types/topojson": "^3.2.2",
"#types/uuid": "^8.3.0",
"#types/ws": "^7.4.0",
"#typescript-eslint/eslint-plugin-tslint": "^4.14.0",
"acorn": "^8.0.5",
"antlr4ts-cli": "^0.5.0-alpha.4",
"eslint": "^7.18.0",
"eslint-plugin-flowtype": "^5.2.0",
"eslint-plugin-import": "^2.22.1",
"eslint-plugin-jsdoc": "^31.3.3",
"eslint-plugin-jsx-a11y": "^6.4.1",
"eslint-plugin-prefer-arrow": "^1.2.2",
"eslint-plugin-react": "^7.22.0",
"eslint-plugin-react-hooks": "^4.2.0",
"identity-obj-proxy": "^3.0.0",
"jest": "26.6.0",
"jest-transform-stub": "^2.0.0",
"jest-websocket-mock": "^2.2.0",
"mock-socket": "^9.0.3",
"monaco-editor-webpack-plugin": "^1.9.1",
"monaco-typescript": "^4.2.0",
"raw-loader": "^4.0.2",
"react-app-rewired": "^2.1.8",
"react-scripts": "^4.0.3",
"react-test-renderer": "^17.0.1",
"selenium-webdriver": "^4.0.0-beta.1",
"ts-jest": "^26.5.2",
"tslint": "^6.1.3",
"typescript": "^4.1.3",
"typescript-eslint-parser": "22.0.0",
"webdriver-manager": "^12.1.8",
"webpack": "4.44.2",
"webpack-bundle-analyzer": "^4.4.0",
"worker-loader": "^3.0.8",
"ws": "^7.4.3"
},
The only promising solution I also could apply is: https://github.com/pmmmwh/react-refresh-webpack-plugin/issues/176#issuecomment-683150213, but it didn't help. I still get the same error. My web worker code is:
/* eslint-disable no-restricted-globals */
/* eslint-disable no-eval */
/* eslint-disable #typescript-eslint/no-unused-vars */
(window as any).$RefreshReg$ = () => {/**/};
(window as any).$RefreshSig$ = () => () => {/**/};
import { ShellInterfaceSqlEditor } from "../../supplement/ShellInterface";
import { PrivateWorker, ExecutionResultType, IConsoleWorkerData } from "./console.worker-types";
const backend = new ShellInterfaceSqlEditor();
const ctx: PrivateWorker = self as any;
The further discussion there about changing the babel loader config is unfortunately beyond me, as I don't configure that myself (what I'm using, however, is react-app-rewired to configure some custom loaders).
What else could I try to fix the issue?

In my case, this error was happening when overwriting Webpack's mode option. After removing the line below I stopped receiving the error.
webpackConfig.mode = 'none'; // this line caused the bug
I believe this is because react-refresh requires webpack to be in mode: 'development' to function properly.
You may want to read about Webpack's modes here: https://webpack.js.org/configuration/mode/. It is also possible that you are setting Webpack mode from the NODE_ENV environment variable.

I tried many of the solutions in this answer and in various Github issues, but none of them resolved the issue for me. Eventually I found a solution via the Webpack sideEffects optimization and config!
tl;dr:
Ensure your Webpack config has an object optimization set and that the optimization object has an attribute sideEffects set to true. Seems like nx and potentially cra or craco defaults this to false, leading to unused React components being imported in WebWorker bundles if they're exported as part of a "barrel" file
If you're importing your own shared ui package which exports React components and some non-React components, then you need to specify the sideEffects config in your package's package.json file to ensure that the React components are marked as "pure" and safe to prune. See below for more details
After inspecting the bundles of my WebWorker, I realized that some React components were being bundled into the worker bundle from worker-loader, even though they weren't being used in the worker. At least one of these cases was happening in our app because we have a shared package which contained some React components and other normal TS utils.
Our WebWorker was importing a value (named export) from this package and for some reason, the entire package was being included in the WebWorker – including the React components that were not being used anywhere! The React Fast Refresh plugin (which is installed / used by CRA by default) then was augmenting our WebWorker bundle with the changes necessary to support hot refresh / reloading (calls to $RefreshReg$ and co).
Some Github issues regarding this problem referenced a Webpack tree shaking optimization called sideEffects, which you can read more about at https://webpack.js.org/guides/tree-shaking/. Here's the relevant bit:
The new webpack 4 release expands on this capability with a way to provide hints to the compiler via the "sideEffects" package.json property to denote which files in your project are "pure" and therefore safe to prune if unused.
In your package's package.json, you can either specify "sideEffects": false to mark the whole package as "pure" and safe to prune if unused, or you can specify the specific exports / paths that do have side effects, eg for us:
"sideEffects": [
"./src/styles/*"
],
However, setting this value didn't work for our app immediately, which was confusing. Eventually, I ran into a thread about this for nx where a very helpful comment noted that their Webpack config was disabling the sideEffects optimization for Webpack: (https://github.com/nrwl/nx/issues/9717#issuecomment-1163533981)
I found that Nx is passing optimization: { sideEffects: false } to webpack, which explicitly turns off tree shaking regardless of your package.json contents. The library that was not being tree shaken in my original issue (lodash-es) already has it's own package.json where it specifies the required setting to facilitate optimal tree shaking, however Nx was turning off tree shaking in Webpack globally, so that it doesn't happen at all for any library or any code in the project.
I tried explicitly setting webpackConfig.optimization.sideEffects = true in my app and boom! Issue resolved, React components being excluded from the WebWorker bundle.

You can try worker-plugin instead of worker-loader. I have been running into the same issue for a long time before trying worker-plugin.

I've also stumbled on this issue on a CRA project
I'm not using typescript for the Web Worker but adding this helped fix the error. (BTW I've only found it thanks to your question. Thanks!)
web.worker.js
if (process.env.NODE_ENV != 'production') {
global.$RefreshReg$ = () => {};
global.$RefreshSig$ = () => () => {};
}
Maybe if you try (global as any) it would work?
Another thing I'm doing is I only import libraries at the top and any code that is used by both main and the worker is added with a require before the usage
e.g.
web.worker.js
const generateSingle = async (client) => {
const mark = `generate for: ${client.id}`;
performance.mark(mark);
const { BillingReportDocument } = require('../pdf/PdfBillingReport');
/* ... */
}
Otherwise I get a different error like "browser is not defined" it's related to emotion/react being used in that file

Related

cannot remove google-recaptura v2 form devDependencies

I tried to remove this types from dev dependencies in every possible way but no luck any idea what is the issue ?
"devDependencies": {
"#types/react-google-recaptcha": "^2.1.3"
}

How to solve this MERN stack filebase64 error?

import FileBase from 'react-file-base64';
I get an error after I hover the triple dot indicator in VS Code.
My setup has already been successful (other input fields have successfully inserted on the MongoDB Cloud) aside from the filebase64 part of inserting an image.
module "d:/nodejs/memories_project/client/node_modules/react-file-base64/build/build.min"
Could not find a declaration file for module 'react-file-base64'. 'd:/nodejs/memories_project/client/node_modules/react-file-base64/build/build.min.js' implicitly has an 'any' type.
Try npm i --save-dev #types/react-file-base64 if it exists or add a new declaration (.d.ts) file containing declare module 'react-file-base64';ts(7016)
Here are the dependencies of my package.json:
"dependencies": {
"#material-ui/core": "^4.9.10",
"#material-ui/icons": "^4.9.1",
"#testing-library/jest-dom": "^4.2.4",
"#testing-library/react": "^9.3.2",
"#testing-library/user-event": "^7.1.2",
"axios": "^0.19.2",
"moment": "^2.27.0",
"react": "^16.12.0",
"react-dom": "^16.12.0",
"react-file-base64": "^1.0.3",
"react-redux": "^7.1.3",
"react-scripts": "3.4.1",
"redux": "^4.0.5",
"redux-thunk": "^2.3.0"
},
If the value is not being saved on the database, that means it is empty or does not exist. Check if the name of the field in the model file (/server/models/) is the same as you have in the Form file (/client/src/components/).
Now the error message has nothing to do with the actual problem.
This happens because react-file-base64 doesn't provide any typing. To get rid of the error you will need to declare the module in a .d.ts file.
To do it, create a .d.ts file (e.g. index.d.ts) in your project root (where the package.json is located) with the following code:
declare module 'react-file-base64';
Or you can declare all with
declare module '*';
I had a similar issue and spent over two hours trying to debug. It can be from a range of issues, my silly mistake was that I had the multiple option set to true when I had not configured it for multiple image uploading.
My code fix as an example.
<FileBase
type="file"
multiple={false}
onDone={({base64}) => setListingData({ ...listingData, selectedFile: base64})}
/>
All you need is to change the Component, the latest I see on its documentation is using FileBase64 not FileBase
So change it into > import FileBase from 'react-file-base64';
Source

Gatsby Develop works, Gatsby Build fails: Loader to handle File Type Missing

First off, I'm new to React/Gatsby. I'm not new to Jekyll, Lando, Drupal, WordPress, basic Git, HTML5/CSS3. I am not strong with JS. Ok, that's out of the way.
I've a got a simple one page site (splash page) that will evolve into a multi-page site. I decided to try Gatsby. The gatsby develop command works well, and I have no es-lint errors for unused variables and such. The gatsby build command produces an error that seems like a super basic thing. There are only two pages in the site — a 404 page and an index. If I remove the 404 page, I get the same error on the index page. Gatsby/Webpack seems to choke on the first piece of content being passed:
JHogue:civicpolicy jhogue$ gatsby build
success open and validate gatsby-configs — 0.006 s
success load plugins — 0.131 s
success onPreInit — 0.166 s
success delete html and css files from previous builds — 0.008 s
success initialize cache — 0.006 s
success copy gatsby files — 0.068 s
success onPreBootstrap — 0.006 s
success source and transform nodes — 0.048 s
success building schema — 0.154 s
success createPages — 0.000 s
success createPagesStatefully — 0.024 s
success onPreExtractQueries — 0.000 s
success update schema — 0.085 s
success extract queries from components — 0.050 s
success run graphql queries — 0.022 s — 4/4 197.54 queries/second
success write out page data — 0.003 s
success write out redirect data — 0.001 s
success onPostBootstrap — 0.001 s
info bootstrap finished - 3.259 s
error Generating JavaScript bundles failed
Error: ./.cache/async-requires.js 8:11
Module parse failed: Unexpected token (8:11)
You may need an appropriate loader to handle this file type.
| exports.components = {
| "component---src-pages-404-js": function componentSrcPages404Js() {
> return import("/Users/jhogue/github/civicpolicy/src/pages/404.js"
| /* webpackChunkName: "component---src-pages-404-js" */
| );
# ./.cache/production-app.js 18:0-45 21:23-36 26:23-36
Since it is just a splash page, there are no data feeds, no markdown files, no arrays of pages to iterate over. Its very simple.
My dependency list is as follows:
"dependencies": {
"css-mqpacker": "^7.0.0",
"gatsby": "^2.0.117",
"gatsby-cli": "^2.4.9",
"gatsby-plugin-react-helmet": "^3.0.6",
"gatsby-plugin-sass": "^2.0.10",
"gatsby-source-filesystem": "^2.0.20",
"gatsby-transformer-json": "^2.1.8",
"gatsby-transformer-remark": "^2.2.4",
"node-sass": "^4.11.0",
"react": "^16.8.1",
"react-dom": "^16.8.1",
"react-helmet": "^5.2.0"
},
"devDependencies": {
"babel-eslint": "^9.0.0",
"eslint": "^5.13.0",
"eslint-config-airbnb": "^17.1.0",
"eslint-plugin-import": "^2.16.0",
"eslint-plugin-jsx-a11y": "^6.2.1",
"eslint-plugin-prettier": "^2.0.1",
"eslint-plugin-react": "^7.12.4",
"prettier-eslint": "^8.8.2"
}
Any pointers would be appreciated. Thanks.
This looks like it might be a Node version issue. Gatsby recommends Node 8 or higher. Can you run node --version and see if you're using a high enough Node version?
If you need a newer version of Node, nvm is a great way to make switching Node versions easier.

How to add React infinite scrolling to a table in ruby on rails

We are adding infinite scrolling to a table in an old project based on ruby on rails. We tried the library react-infinite but it did not work.
We installed it through bower
"dependencies": {
"bootstrap": "~3.3.7",
"bootstrap-sass": "~3.3.7",
"jquery": "~1.9.1",
"react": "~0.13.3",
"react-simpletabs": "^0.7.0",
"react-bootstrap-treeview": "0.1.0",
"sisyphus": "1.1.3",
"prototypejs": "1.7.1",
"highcharts": "4.2.7",
"js-grid": "1.5.3",
"jquery-colorbox": "1.5.10",
"react-infinite": "*"
}
In application.js, we import it using
//= require react-infinite
Then we use it like this:
<react-infinite containerHeight={200} elementHeight={40}>
<ContentTable
data={this.state.tableData}
filterText={this.state.filterText}
onUserClick={this.handleUserClick}
dataType={this.props.dataType}
showPublic={this.state.publicCheckbox}
/>
</react-infinite>
But it did not make any difference. ContentTable is a customized table. And in the console, there is an error:
How can I make it work on a table? Any help would be appreciated.

The Angular 2 final release and the documentations "The Tour of Heroes"

Last 2 days I've been looking at the Angular 2, I'm new to it so I went straight "the official documentation" which is the Tour of Heroes example, it's ok "Just ok" tutorial and I followed the steps and I could understand a lot from it, when I reached the HTTP part and how to get access to Data sources issues started to pop up, I'm not sure if it's me very beginner in this OR the documentation is not up-to-date with the final release, :/ Google people, a big company and you guys can not assign this task to a team who take care of the documentation and keeps it updated with the releases? My opinion it's such task is mandatory for some reasons and it's the company responsibility or the Angular 2 project team's responsibility, it's new release and it's completely different from the angularjs 1.x so don't you guys think that you should provide solid reliable support in the form of up-to-date documentation right? Unless you want React to be in the lead ;)
If anyone knows good documentation for http and how to retrieve modify save and delete data and it's compatible with the final release please share it, now the issue that I collided with in the Tour of Heroes tutorial is that I get error because of this line:
import { InMemoryWebApiModule } from 'angular-in-memory-web-api';
can't find the module 'angular2-in-memory-web-api'
I was ok I'm not gonna use this in memory web Api, so I created asp.net web Api and it works fine and here is the GetHeroes method in the Heroes Controller it's so straight forward:
// GET: api/Heroes
public IQueryable<Hero> GetHeroes()
{
return db.Heroes;
}
of course I test the method and it returns all the heroes so the api working just fine, now this's the method from the hero.service.ts :
getheroes(): Promise<Hero[]>
{
return this.http.get(this.heroesUrl)
.toPromise()
.then(response => response.json().data as Hero[])
}
ok I get no errors but data is nt showing like literally nothing however when I remeove .data as Hero[] part I get enter image description here
and once I click on "one hero" I get nothing as well and the url like this : 4200/details/undefined notice instead of the hero Id I get undefined ?! anyway I noticed that in many videos of some people "tutoring" angular 2 that there is no common steps to work Http for accessing data and doing CRUD operation through api , every one doing it in different way and the thing is when I try to follow it's just not working with what I have and this's from my package.json:
"dependencies": {
"#angular/common": "2.0.0",
"#angular/compiler": "2.0.0",
"#angular/core": "2.0.0",
"#angular/forms": "2.0.0",
"#angular/http": "2.0.0",
"#angular/platform-browser": "2.0.0",
"#angular/platform-browser-dynamic": "2.0.0",
"#angular/router": "3.0.0",
"core-js": "^2.4.1",
"rxjs": "5.0.0-beta.12",
"ts-helpers": "^1.1.1",
"zone.js": "^0.6.23"
},
"devDependencies": {
"#types/jasmine": "^2.2.30",
"angular-cli": "1.0.0-beta.15",
"codelyzer": "~0.0.26",
"jasmine-core": "2.4.1",
"jasmine-spec-reporter": "2.5.0",
"karma": "1.2.0",
"karma-chrome-launcher": "^2.0.0",
"karma-cli": "^1.0.1",
"karma-jasmine": "^1.0.2",
"karma-remap-istanbul": "^0.2.1",
"protractor": "4.0.5",
"ts-node": "1.2.1",
"tslint": "3.13.0",
"typescript": "2.0.2"
}
So anyone can help or share something official and compatible with the final release? I wish the Google people pay attention and take care of the documentations, not everyone is an expert.
You must to fix the line:
import { InMemoryWebApiModule } from 'angular-in-memory-web-api';
To:
import { InMemoryWebApiModule } from 'angular2-in-memory-web-api';
You missed the 2 ...
Also in in-memory-data.service.ts file fix it
There is a mistake in documentation

Resources