"Syntax error: Unexpected keyword" in random places in react-scripts - javascript

I've recently updated my Javascript project from Webpack to react-scripts.
My code structure is fairly simple. I have a src folder with an index.js that just renders the DOM like this:
import ReactDOM from 'react-dom';
import Index from './pages/index';
ReactDOM.render(<Index />, document.querySelector('#root'));
and my Index which is just a single page that renders some stuff like this:
/**
* Injected styles for this component
*/
const styles = theme => ({
...
})
class Index extends Component {
...
}
export default withRoot(withStyles(styles)(Index));
in my package.json I use react-scripts to start the app.
When running npm run start the dev-webserver starts.
I can change a single letter, save the file, the dev-webserver restarts, and then I get random syntax errors throughout the code. They look like this:
./src/pages/index.js
Syntax error: Unexpected keyword 'return' (144:7)
142 |
143 | if(!this.state.data){
> 144 | return null;
| ^
145 | }
146 |
147 | return <Grid>
or this
./src/pages/index.js
Syntax error: Unexpected token (76:11)
74 | */
75 | render() {
> 76 | const { classes } = this.props;
| ^
77 |
78 | return (
79 | <div className={classes.root}>
or on any other part of the project. They keep happening until I restart npm.
I've tried to delete code until it doesn't happen anymore. Then I end up with a single React.Component that only renders a div with text.
I've tried to work on another project; the same issue happens there.
The project works fine on other devices.
Things I've tried:
delete node_modules folder
downgrade dependencies
delete project and clone again
use different browser
restart pc
change back to webpack
try to search online for the error
My node version is:
v6.9.1
My npm version is:
v6.8.0

Turns out my node version is very old (2016).
I updated node to the newest version and it stopped happening.

Related

I don't understand why it is having this error. Even if the directory is correct and also the filename

IMAGE OF THE ERROR
Android Bundling failed 5334ms
Unable to resolve module ../model/weights.bin from
D:\Repos\BANANAFILE\helpers\tensor-helper.js:
None of these files exist:
model\weights.bin(.native|.android.ts|.native.ts|.ts|.android.tsx|.native.tsx|.tsx|.android.js|.native.js|.js|.android.jsx|.native.jsx|.jsx|.android.json|.native.json|.json)
model\weights.bin\index(.native|.android.ts|.native.ts|.ts|.android.tsx|.native.tsx|.tsx|.android.js|.native.js|.js|.android.jsx|.native.jsx|.jsx|.android.json|.native.json|.json)
10 |
11 | const modelJson = require('../model/model.json');
12 | const modelWeights = require('../model/weights.bin');
React-native uses es6 imports so do this instead
import modelJson from "../model/model.json"
import modelWeights from "../model/weights.bin"

Multi module projects with create-react-app

I have a project called Frontend-Core-Components which contains my App component.
I have another project (let's just call it Alpha for now) which containsAlphaApiService, which I pass to the App component via its props, I do this in Alpha's index.tsx
Alpha uses Create-react-app, I'm using rescript to modify the Webpack config to add Frontend-core-components as a module, Inside this Webpack configuration, I use resolve.alias to map imports from Alpha index.tsx to the Frontend-Core-Components.
It all seems to work, except when I run the build from Alpha project, I encounter the following.
SyntaxError: /Users/coolguy/project/alpha/src/index.tsx: Unexpected token (9:11)
7 |
8 | window.onload = () => {
> 9 | render(<App apiService={new AlphaApiService()} />,
document.getElementById('root'))
| ^
10 | }
11 |
any ideas?
You need to compile your import module, before importing it.
I would suggest checking out this project to create React component libraries.
https://github.com/KaiHotz/react-rollup-boilerplate
Or you can include the Frontend-Core-Components in your ts-loader(or babel-loader) rule.

How to mock LayoutAnimation when testing React Native with Jest

I am using Jest and react-native-testing-library to test my components.
In one of my components I have the following code:
const handleToggleFilters = () => {
LayoutAnimation.configureNext(LayoutAnimation.Presets.spring);
setPostFiltersActive(!postFiltersActive);
};
However, when testing my component, I get the following error
TypeError: require(...).configureNextLayoutAnimation is not a function
82 |
83 | const handleToggleFilters = () => {
> 84 | LayoutAnimation.configureNext(LayoutAnimation.Presets.spring);
| ^
85 | setPostFiltersActive(!postFiltersActive);
86 | };
87 |
I added jest.mock('react-native') to my setup.js file but it then started complaining about other missing entities through the rest of my test suite ... do I have to mock the entire react-native library for this to work?
What is the best way around this?
After looking at certain tests from react-native on github, it looked like they simple mocked the file themselves.
// Libraries/Components/Keyboard/__tests__/Keyboard-test.js
jest.mock('../../../LayoutAnimation/LayoutAnimation');
So in my setup.js file I simply did
jest.mock(
'../node_modules/react-native/Libraries/LayoutAnimation/LayoutAnimation.js',
);
And my tests passed.

Expo Error when Running AWS App on web browser only (AmplifyI18n)

My aws-react-native app runs perfectly on Android (using expo), but when I try to use the "w" option in expo and then run it in the browser, I get the following error page. It looks to me some lib is missing or something like that, does anyone knows what I could try to make it available on the web?
Tested on Android and it has worked fine - the problem seems to happen just in the browser and it seems to be aws-amplify related.
My App.js imports:
import * as Localization from 'expo-localization';
import React, { Component } from 'react';
import { StyleSheet, Text, View } from 'react-native';
// Necessary for "Auth" service
import Auth from '#aws-amplify/auth';
import Analytics from '#aws-amplify/analytics';
import { Authenticator } from 'aws-amplify-react-native';
import awsconf from './source/aws-exports';
Auth.configure(awsconf);
Analytics.configure(awsconf);
//Necessary for Translation
console.log(Localization.locale);
import { I18n } from 'aws-amplify';
import dict from './source/translations';
I18n.setLanguage(Localization.locale);
I18n.putVocabularies(dict);
...
Error Page:
×
ReferenceError: dict is not defined
Module.../../../../../../../../../../../environment/node_modules/aws-
amplify-react-native/dist/AmplifyI18n.js
node_modules/aws-amplify-react-native/dist/AmplifyI18n.js:14
11 | * and limitations under the License.
12 | */
13 |
> 14 | export default dict = {
15 | 'fr': {
16 | 'Loading...': "S'il vous plaît, attendez",
17 | 'Sign In': "Se connecter",
View compiled
__webpack_require__
/home/ubuntu/environment/webpack/bootstrap:724
721 | };
722 |
723 | // Execute the module function
> 724 | modules[moduleId].call(module.exports, module, module.exports,
hotCreateRequire(moduleId));
| ^ 725 |
726 | // Flag the module as loaded
727 | module.l = true;
View compiled
fn
/home/ubuntu/environment/webpack/bootstrap:101
98 | );
99 | hotCurrentParents = [];
100 | }
> 101 | return __webpack_require__(request);
| ^ 102 | };
There are things you need to install and set up.
Ensure you’re using the latest version of babel-preset-expo
Install react-native-web, and react-dom.
Add the property “web” to the expo.platforms array in your
app.json
"expo": {
"platforms": ["web"]
}
Then run expo start with the latest version of the expo-cli
after the bundler has started, you can press the w key to open
your app in the browser.
NOTE: Because most libraries in the React-native community do not support the Web, it may not work as well as RNW can expect.
Try to remove the dict = from your export default dict =, so that it looks like:
export default {
'fr': {
...

Testcafe wont recognise React

I'm trying to run my first testcafe test but it's proving arduous.
testcafe -e chrome client/routes/Lookup/components/testcafe/lookup-test.js
SyntaxError: client/routes/Lookup/components/Lookup.js: Unexpected token (60:8)
58 | if (error.status && error.status !== 404) {
59 | return (
> 60 | <NetworkIssues code={error.status} />
| ^
61 | );
62 | }
63 |
at Object.<anonymous> (client/routes/Lookup/components/testcafe/lookup-test.js:1:1)
lookup-test.js
import Lookup from '../Lookup';
import React from 'react';
import { waitForReact } from 'testcafe-react-selectors';
fixture('Lookup Component').page('http://localhost:3000/web/lookup').beforeEach(async () => {
await waitForReact();
});
test('foo', async (x) => {
await x
.typeText('customerName', '07450118811')
.expect('customerName.value').contains('07450118811');
});
My code doesn't have any errors. It compiles and works fine and passes all my jest and enzyme unit testing. But I can't find any guidance online for this. As you can see the ignore errors flag is used to no avail.
Cheers.
When you start TestCafe, all your test code is transpiled as a first step before execution. What is executed is the result of this transpilation process and not your original source code, even if your code is pure JavaScript.
The imported file client/routes/Lookup/components/Lookup.js is a JSX file, and since it is imported in the TestCafe code, il will be first transpiled to javascript before starting test execution.
The TestCafe transpilation process (at the time of writing - it may change in the future) is not configured to handle JSX files.
Therefore, you cannot import files that cannot be transpiled into pure JS by TestCafe.
try commenting this out
//import Lookup from '../Lookup'
TestCafe can't handle JSX outside of class components. If you are using react, and create a function that returns JSX, testCafe will throw up on it. You can resolve it by just creating a new class component instead. see TestCafé + React JSX error (unexpected Token) for more details.

Categories

Resources