How to resolve service worker error in react? - javascript

I am getting a service worker error while running my react app.
Can you please help me why it's getting the error. Screenshot link is given below,
Servier worker error message
import React from 'react';
import ReactDOM from 'react-dom';
import { createStore, applyMiddleware, compose } from 'redux';
import rootReducer from './reducers/rootReducer';
import {Provider} from 'react-redux';
import thunk from 'redux-thunk';
import config from './config/index'
import App from './App';
import './index.scss'
import * as serviceWorker from './serviceWorker';
const store = createStore(rootReducer,
compose(
applyMiddleware(thunk.withExtraArgument({}))
)
);
ReactDOM.render(<Provider store={store}><App /></Provider>, document.getElementById('root'));
serviceWorker();

It's a simple mistake =)
Look at this line:
import * as serviceWorker from './serviceWorker';
and then look here:
serviceWorker();
On the first line of code you're importing the whole module into your file's scope as 'serviceWorker'. On the second line you're trying to call that module. But you cannot call a module, it's not allowed. It's also what the error message says right at the top of your screenshot.
I think what you actually should be doing is something like this:
import { register } from './serviceWorker';
...
...
register();
or something similar. It might also be registerServiceWorker or something like that. Look at the ./serviceWorker.js file and find out.
One thing to note: I would seriously consider _not using_ Service Workers in your project until you know exactly how they work, what they are etc. It is SUPER EASY to cause a lot of problems by using Service Workers without really knowing them.

Related

Why pdfjs-dist is not working for Internet Explorer?

I have a react build using yarn. It produces three files:
main.hash1.chunk.js
2.hash2.chunk.js
pdf.worker.hash3.chunk.js
Under IE, the last file errors with Error: 'Promise' is undefined
core-js is already setup but it doesn't appear to be included in pdf.worker.hash3.chunk.js.
index.js:
import React from "react";
import ReactDOM from "react-dom";
import {
BrowserRouter as Router,
Route,
Switch
} from "react-router-dom";
import { Theme } from "./theme";
import { Chart } from "./pages/Chart";
import "typeface-libre-franklin";
import "typeface-roboto";
import "./polyfills.js";
import pdfjs from "pdfjs-dist";
import "core-js";
ReactDOM.render(
<Theme>
<bunch of other tags />
</Theme>,
document.querySelector("#root")
);
Turns out, that in my build environment, the issue was resolved with having the correct version of pdfjs-dist installed.
I had 2.6.347 and had to downgrade to 2.2.228. Once that was done, it no longer made a pdf.worker.hash.worker.js file and instead made a longer-hash.worker.js file that works with what I needed it to.

Module not found :Can't resolve './components/counter' in 'C:/...demo\counter-app\src'

I am totally new to React and i'm following tutorials (Programming with MOSH) in youtube but i'm stuck with this error, unable to resolve after finding similar questions.
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import "bootstrap/dist/css/bootstrap.css";
import Counter from './components/counter';
//import * as Counter from './components/counter'; //tried this method too
ReactDOM.render(
<Counter />,
document.getElementById('root')
);
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
serviceWorker.unregister();
counter.jsx
import React, { Component } from 'react';
class Counter extends Component {
render() {
return <h1> Hello world</h1>;
}
}
export default Counter;
in command prompt i had done npm install and npm start after deleting package-lock.json but still the same error
folder structure
Thanks in advance.
Move your components folder inside the SRC this will fix it
Either move components folder inside src folder or change the reference in the import statement to '../component/counter'

React/Redux/Firebase createStore Config

When I try to npm start my project I don't see any error on the terminal. I am new to react-redux-firebase. Here is the error that I can see using my browser:
TypeError: Object(...) is not a function
Screenshot:
Here is the code of index.js:
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import { createStore, applyMiddleware, compose } from "redux";
import rootReducer from "./store/reducers/rootReducer";
import { Provider } from "react-redux";
import thunk from "redux-thunk";
import { reduxFirestore, getFirestore } from "redux-firestore";
import { reactReduxFirebase, getFirebase } from "react-redux-firebase";
import firebaseConfig from "./config/fbConfig";
const store = createStore(
rootReducer,
compose(
applyMiddleware(thunk.withExtraArgument({ getFirebase, getFirestore })),
reactReduxFirebase(firebaseConfig),
reduxFirestore(firebaseConfig)
)
);
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById("root")
);
I am not sure what is wrong I just followed the tutorial on YouTube.
Maybe that YouTube tutorial is out of date. I could reproduce your issue and I guess it is happening because of reactReduxFirebase(firebaseConfig) line in your code within compose.
In the official documentation - which states there are breaking changes - which contains that they removed reactReduxFirebase, please read as follows:
Removed from API: reactReduxFirebase store enhancer (firebase instance is now created by context providers)
In VSCode the IntelliSense shows that reactReduxFirebase is a namespace now and not a function:
So as the migration guide mentioned maybe you can try to remove that line and replace that store enhancer with ReactReduxFirebaseProvider.
For more information please read and follow the Change Snippets part of the documentation. It's pretty detailed with step by step examples.
I hope this helps!

console.log() above import statements in root file does not execute before import

Consider the root index.js file in a React app that does the following:
console.log("INDEX.JS")
import React from 'react';
import { render } from 'react-dom';
import { BrowserRouter as Router } from 'react-router-dom';
import { Provider } from 'react-redux';
//Internal Dependencies
import Auth from './containers/Auth';
import store from './store/store';
import ErrorBoundary from './containers/ErrorBoundary';
//Highcharts config
import highchartsConfig from './globalChartConfig';
//Global styles
import './index.css';
highchartsConfig();
render(
<Router>
<Provider store={store}>
<ErrorBoundary>
<Auth />
</ErrorBoundary>
</Provider>
</Router>,
document.getElementById('root')
);
The import statements are executed BEFORE the console.log statement at the top of this file. a console.log at the top of the Auth.js file will be executed first. Why is that?
The following console.log() is the first thing that logs to the console.
// Auth.js
console.log('AUTH')
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
You must scope all import statements at the top. This restriction allows webpack(not only webpack, any module loader actually) to analyze statically what modules are imported by a module and load them before executing its body.
console.log('first import then log')
import { foo } from 'foo'
Putting code above import throws an eslint warning (import/first)
Why inside index.js console.log fires after the imports and inside
auth.js executes in the expected order?
When calling index.js (entry point which will render the entire application) webpack will bundle every module including those required for App and Auth and then call console.log. When you access Auth.js all modules are already bundled so the only thing left to do is to call console.log.
For a detailed explanation

"Import in body of module; reorder to top import/first" Across Many Files

I have the same error as this answer, except instead of it just occurring in one file it is occurring in many; once I fix it for one file, another just pops up with the same error. I've seen this answer but whenever I run react-scripts start a node_modules folder is created in my src, so that solution isn't viable.
It would be too time consuming to have to fix every file that has this error every time I compile, so how can I get rid of this error? It seems to just be an eslint issue.
you will get this error if you declare variable in between your imports,
import React from 'react';
import axios from 'axios';
const URL = process.env.REACT_APP_API_BASE;
import demoXLXSFile from '../../assets/others/Demo.xlsx';
import './student.list.styles.scss';
declare variables after importing everything,
import React from 'react';
import axios from 'axios';
import demoXLXSFile from '../../assets/others/Demo.xlsx';
import './student.list.styles.scss';
const URL = process.env.REACT_APP_API_BASE;
I found this issue while I was using React.lazy in my existing project. I got this error Failed to compile. :- Import in body of module; reorder to top import/first (with create-react-app).
import React from 'react';
import SelectField from '../inputs/SelectField';
const Questions = React.lazy(() => import('./questions'))
import _ from 'lodash';
Solution:-
Only reorder the position i.e. put all import on top then react.lazy.
import React from 'react';
import SelectField from '../inputs/SelectField';
import _ from 'lodash';
const Questions = React.lazy(() => import('./questions'))
I got this same error when I added an extra semicolon ';' at the end of an import statement.
I suggest removing any extraneous semicolons. This should make the error go away.
Moving every import statement to the top of the file solves the issue.
Happened to me when I put require before import like this:
require('dotenv').config()
import React from 'react';
import ReactDOM from 'react-dom';
...
Solution: Put the require after the imports
If You are using Component Lazy loading then always put lazy load component import code below normal import code.
Correct Example
import First from './first'
const Second = React.lazy(()=>import("./Second))
Incorrect Example
const Second = React.lazy(()=>import("./Second))
import First from './first'
I came across this issue too. I found that you must import all ES6 modules at the top level of your JavaScript files."... the structure of ES6 modules is static, you can’t conditionally import or export things. That brings a variety of benefits.
This restriction is enforced syntactically by only allowing imports and exports at the top level of a module:"
From Dr. Axel Rauschmayer’s Exploring JS:
Wrong
1.
import React ,{useState ,useEffect} from 'react';
import './App.css';
import Post from './Post';
import db from "./firebase"
Right
2.
import React ,{useState ,useEffect} from 'react';
import './App.css';
import Post from './Post';
import db from "./firebase.js"
//this is code firebase.js
const db = firebaseApp.firestore();
const auth = firebase.auth();
const storage = firebase.storage();
export default {db,auth,storage};
When I change the firebase into firebase.js in Snippet 2.
My Error vanished
I had forgotten to add from.
Before:
import UpperBlock;
After:
import UpperBlock from "../components/dashboard/shared/UpperBlock";
Make sure you import well your component and then stop the server and restart it again. It worked for me.
I forgot to add {Component} after importing 'react' library to my project, this solved my issue.
Move all of your imports to the top of the file.
Even in case of a require (that is written in between import statements), this error will come.
e.g.
import 'some_module';
require('some_file');
import 'some_other_module');
This would result in an error.
You would want to do this instead:
import 'some_module';
import 'some_other_module');
require('some_file');
I was facing the same issue when I installed chat.js library in my reactJs project. I solved this issue by moving my chart.Js import to the index.js file
index.js file:
import React from "react";
import ReactDOM from "react-dom";
import { Chart as ChartJS, ArcElement, Tooltip, Legend } from "chart.js"; <--- imported
import "./index.css";
import App from "./App";
ChartJS.register(ArcElement, Tooltip, Legend); <---- imported
If you're experiencing this error in modern versions of react(current version 18.0.0) make sure you're making all your imports before the ReactDOM.createRoot declaration.
For example, I got the error with:
import App from "./App";
import reportWebVitals from "./reportWebVitals";
const root = ReactDOM.createRoot(document.getElementById("root"));
import { Provider } from "./context";
This will result in an error. Instead, import everything before the createRoot:
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import { Provider } from "./context";
const root = ReactDOM.createRoot(document.getElementById("root"));
This will fix the error. Simple fix but it's easy to miss
If I put double Semicolon behind the importing statement than I got "error".you can see difference between two pictures in import './index.css'; is different
For Example :-
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';;
import 'tachyons';
import {robots} from "./Robots";
import reportWebVitals from './reportWebVitals';
import CardList from './CardList';

Categories

Resources