Git/node getting stuck on old .js -file version - node.js

I'm having a weird problem with git/node getting stuck to use an old version of .js-file.
Every once in a while after saving changes (so far only when the code has some errors in it, often after merge conflicts) the file gets somehow stuck in old version when building the app. Everything looks to be ok, VSCode changes the file and shows it just fine, but when trying to build the app, build process (both develop and production) uses the old fileversion with bugs in it.
This same thing is happening both on Win10 and MacOs.
I have found 2 ways to fix this (both are just workarounds)
Rename the file that is causing the problem
the old filename cannot be used even after it has been deleted and recreacted
Clone the branch with new name Re-clone the repository
Here are example files:
InfoComponents.js (this one had the error in it)
import React from 'react';
import Typography from '#material-ui/core/Typography';
import Battery from '#navigil/shared/src/components/SVGs/Battery';
import Box from '#navigil/shared/src/components/Box/Box';
import InfoBadge from './InfoBadge';
const batteryStatus = [80, 50, 15, 5];
const InfoComponents = ({ badges }) => (
<>
<Typography variant='h4'>Status / Warnings / Alarms</Typography>
<Box>
{badges.map((badge, index) => {
const { badgeProps, imageProps, imageComponent: Image } = badge;
return (
<InfoBadge key={index} {...badgeProps}>
<Image {...imageProps} />
</InfoBadge>
);
})}
</Box>
</>
);
export default InfoComponents;
Dashboard.js (this imports InfoComponents)
import React from 'react';
import Typography from '#material-ui/core/Typography';
import styled from 'styled-components';
import Battery from '#navigil/shared/src/components/SVGs/Battery';
import Box from '#navigil/shared/src/components/Box/Box';
import Button from '#navigil/shared/src/styledTheme/Components/Button';
import InfoComponents from './InfoComponents';
import { badges } from './testVariables';
const StyledButton = styled(Button)`
max-width: 100px;
`;
const NewWatchDashboard = () => (
<>
<InfoComponents badges={badges} />
</>
);
export default NewWatchDashboard;
And here is the parse error i'm receiving when build fails:
./src/InfoComponents/Dashboard.js
Line 7:28: Parse errors in imported module './InfoComponents': Line 14: Unexpected token
12 | <Box>
13 | {badges.map((badge, index) => ({
> 14 | <InfoBadge key={index} {...badgeProps}>
| ^
15 | <Image {...imageProps} />
16 | </InfoBadge>;
17 | }))} (14:9) import/namespace
Line 7:28: Parse errors in imported module './InfoComponents': Line 14: Unexpected token
12 | <Box>
13 | {badges.map((badge, index) => ({
> 14 | <InfoBadge key={index} {...badgeProps}>
| ^
15 | <Image {...imageProps} />
16 | </InfoBadge>;
17 | }))} (14:9) import/default
As you can see from above, the code in InfoComponents.js doesn't match the code in error message.
Creating a sandbox for this is kind of hard, because everything works just fine if I'm creating all of this from scratch. So it definetly looks to be a problem with Git.
Any ideas what could cause this and how to prevent it from happening?
Any ideas how to fix this easily when it happens?
-Jukka

Most probably the issue is with your local Git working tree.
Give a try with following:
#Copy the code from `InfoComponents.js` to some other file.
git rm --cached InfoComponents.js
#Commit the change
# add back the file with backed up content
# commit again
This might solve the issue.
Or
Try to clean your local git work tree:
git gc --prune=now
And check if your changes are reflected correctly.

Related

Invalid return value in simple jest test

I am testing a view for Home component for React Native 0.68.2/jest 29.0. The simple test case is copied from jest doc:
import React from 'react';
import { NavigationContainer } from '#react-navigation/native';
import { render, cleanup, screen, fireEvent } from "#testing-library/react-native";
import App from '../App';
describe ('App ', () => {
//afterEach(cleanup);
test ('shall stack screens', async () => {
const component = (<NavigationContainer>
<App />
</NavigationContainer>);
const {getByText} = render(component);
await waitFor(() => getByText('AppSplash'));
})
})
Here is the App.js:
import React, {useState, useContext, Component} from 'react';
import { NavigationContainer } from '#react-navigation/native';
import { createStackNavigator } from '#react-navigation/stack';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import SplashScreen from './src/components/splashscreen/SplashScreen';
import SysError from './src/components/app/SysError';
import Bye from "./src/components/app/Bye";
import Verif1 from './src/components/signup/Verif1';
import Signup from './src/components/signup/Signup';
import TermCondition from './src/components/common/TermCondition';
import AppScreen from "./src/components/app/AppScreen";
const Stack = createStackNavigator();
export default function App() {
return (
<SafeAreaProvider>
<NavigationContainer>
<Stack.Navigator InitialRouteName="AppSplash">
<Stack.Screen name="AppSplash" component={SplashScreen} options={{headerShown:false}}/>
<Stack.Screen name="AppSysError" component={SysError} options={{headerShown:false}} />
<Stack.Screen name="AppScreen" component={AppScreen} options={{headerShown:false}} />
<Stack.Screen name="AppVerif1" component={Verif1} options={{headerShown:false}} />
<Stack.Screen name="AppSignup" component={Signup} options={{headerShown:false}} />
<Stack.Screen name="TermCondition" component={TermCondition} options={{headerShown:false}} />
<Stack.Screen name="Bye" component={Bye} options={{headerShown:false}} />
</Stack.Navigator>
</NavigationContainer>
</SafeAreaProvider>
);
};
Here is the output of yarn jest.
● Invalid return value:
`process()` or/and `processAsync()` method of code transformer found at
"/Users/macair/Documents/code/js/xyz_app6/node_modules/react-native/jest/assetFileTransformer.js"
should return an object or a Promise resolving to an object. The object
must have `code` property with a string of processed code.
This error may be caused by a breaking change in Jest 28:
https://jestjs.io/docs/upgrading-to-jest28#transformer
Code Transformation Documentation:
https://jestjs.io/docs/code-transformation
I just started using jest and none of solutions found this error works.
The error process() or/and processAsync() method of code transformer found at indicates that the issue is jest v28.x doesn't support react-native v68.x. You will either need to downgrade to jest v27.x or upgrade to react-native v70.x.
See this commit on the react-native github: https://github.com/facebook/react-native/commit/b5ff26b0b97d6cd600bdb9c33af866971ef14f9c
Jest 28 removed support for returning a string in the process method of a transformer (https://jestjs.io/docs/upgrading-to-jest28#transformer).
This PR changes assetFileTransformer to return an object instead of a string.
The above commit is a fix for the issue you are seeing. It was merged in. If you look closely at the commit message, underneath which you will find a list of tags associated with the commit. These tags will tell you which releases contain this commit.
The commit message shows the below tags.
v0.70.1 v0.70.0 v0.70.0-rc.4 v0.70.0-rc.3 v0.70.0-rc.2 v0.70.0-rc.1 v0.70.0-rc.0 latest
These tags tell us that the commit first made it into the 0.70 release candidate, eventually landing in the 0.70 stable release. It is also present, as you'd expect, in the 0.70.1 stable.
See for more info on releases https://reactnative.dev/contributing/release-faq
Either upgrade to react-native 70.x or downgrade Jest to 27.x.

Deploying NextJS project to my own server (npm run build triggers module not found error)

I have built a NextJS project and I'm ready to deploying it to a staging server for testing (running AlmaLinux 8). I have installed node version 16.8.0.
I've copied the entire contents of my project to my server and run npm run build but I then get the error:
build
> next build
info - Loaded env from /var/www/html/CrashCatch/CrashCatchDocs_Testing/.env
Failed to compile.
./pages/[...].tsx:2:23
Type error: Cannot find module '../components/TopHeader' or its corresponding type declarations.
1 | import Head from 'next/head'
> 2 | import TopHeader from "../components/TopHeader";
| ^
3 | import Link from 'next/link'
4 | import {useRouter} from "next/router";
5 | import {getSlugFromUrl} from "../JSFuncs/HelperFunctions";
Below is a screenshot showing the directory structure
In the `./pages[...].tsx I have the following
import Head from 'next/head'
import {getSlugFromUrl} from "../JSFuncs/HelperFunctions";
import UserHelpContainer from "../components/Articles/UserHelpContainer";
import UserSidebar from "../components/Sidebar/UserSidebar";
import useArticle from "../hooks/useArticle";
import {useEffect, useState} from "react";
import useCrashCatch from "../hooks/useCrashCatch";
import TopHeader from "../components/TopHeader";
export default function Home() {
const slug = getSlugFromUrl();
const {loading, publishedArticle, errors, refetch} = useArticle(slug);
const [mobileSidebarOpen, setMobileSidebarOpen] = useState(false);
const {crashcatch} = useCrashCatch('12345', "123456", "1.0.0");
useEffect(() => {
(
async function() {
await refetch();
}
)();
}, [slug]);
return (
<>
<div className="w-full h-full min-h-full overflow-none absolute">
<Head>
<title>Crash Catch Documentation</title>
<link rel="icon" href="/favicon.ico" />
<meta name='description' content={publishedArticle !== null && typeof publishedArticle !== typeof undefined ? publishedArticle.metaDescription : ''} />
<meta name='keywords' content={publishedArticle !== null && typeof publishedArticle !== typeof undefined ? publishedArticle.metaKeywords : ''} />
</Head>
<TopHeader mobileSidebarOpen={mobileSidebarOpen} setMobileSidebarOpen={setMobileSidebarOpen} />
<div className='flex flex-row h-full overflow-y-scroll'>
<UserSidebar slug={slug} mobileSidebarOpen={mobileSidebarOpen} setMobileSidebarOpen={setMobileSidebarOpen} />
<UserHelpContainer slug={slug} loading={loading} errors={errors} article={publishedArticle} />
</div>
</div>
</>
)
}
And in the TopHeader I have the following:
I am declaring TopHeader as follows (I've not included the whole thing as don't think its relevant)
const TopHeader = React.memo(function TopHeader(props: TopNavProps)
If the path is correct, you might not be exporting TopHeader as default?
export default TopHeader; // This will allow for generic import
And then to import:
import TopHeader from '../components/TopHeader'; // Can now use TopHeader
Edit: Included code blocks, cleaned answer and moved ramble to bottom...
I have never answered a question, so I planned on just commenting as this is more or less a question... But I must have more reputation to comment... Apologies..
I figured out my problem, thanks for the suggestions as it made me look at something and figure out the issue.
It was a rather dumb reason, where my SFTP client didn't fully upload and instead asked me a question which was hidden, so I didn't see it and therefore, only the top level directories uploaded, but deeper directories were missing some files hence the module not found error.
After getting this to work it it was an issue with CSS, this was to do with Tailwind purging CSS classes so had to add the following to tailwindcss.confnig.js
module.exports = {
purge:{
enabled: true,
content: [
'./pages/**/*.{js,ts,jsx,tsx}',
'./components/**/*.{js,ts,jsx,tsx}',
'./components/*.{js,ts,jsx,tsx}',
'./JSFuncs/*.{js,ts,jsx,tsx}'
// Add more here
]
},

Troubleshooting SVG error in Gatsby build

I'm trying to get a simple Gatsby site online -- gatsby develop works fine but on gatsby build I get this error message:
UNHANDLED REJECTION
- Error in parsing SVG:
- Unencoded <
- Line: 0
- Column: 2
- Char: <
I'm not explicitly using any SVGs so struggling to troubleshoot this - any advice?
My project is here, adapted from the lumen starter theme.
In your Icon.js (line 14) file you are using a <svg>. This is causing your issue:
// #flow strict
import React from 'react';
import styles from './Icon.module.scss';
type Props = {
name: string,
icon: {
viewBox?: string,
path?: string
}
};
const Icon = ({ name, icon }: Props) => (
<svg className={styles['icon']} viewBox={icon.viewBox}>
<title>{name}</title>
<path d={icon.path} />
</svg>
);
export default Icon;
When dealing with SVG I would recommend using gatsby-plugin-react-svg or using a React built-in usage.
With gatsby-plugin-react-svg you just to isolate the SVG in a separate folder that must only contain SVGs):
{
resolve: 'gatsby-plugin-react-svg',
options: {
rule: {
include: /assets/
}
}
}
Then import it as a React component:
import Icon from "./path/assets/icon.svg";
// ...
<Icon />;
React built-in usage (only available with react-scripts#2.0.0 or higher, and react#16.3.0 or higher, more details in https://create-react-app.dev/docs/adding-images-fonts-and-files/):
import { ReactComponent as FacebookIcon } from '../images/svg/facebookF.svg';
import { ReactComponent as Email } from '../images/svg/email.svg';
...
<FacebookIcon />
<Email />
Since you are extending from a starter theme, remove that component and it's using from your project and add it on-demand if needed.
You can read this StackOverflow answer for further details about dealing SVG in Gatsby.

My file is failing right at the very first line, import React from "react", with a TypeError: Object(...) is not a function

I'm working with the basic Gatsby starter site and it compiles just fine, but the browser just shows the error mentioned in the title as well as a couple warnings.
It's probably important to note that the error is gone when I completely remove the StaticQuery piece so the IndexPage component is just the opening and closing Layout tags. This gets rid of the error and the browser shows the header+footer of the Gatsby starter site.
I've made sure that my versions of react and react-dom are up to date in the package.json, I've reinstalled the packages via npm install, I've tried other versions of react, nothing is working.
The file that is failing (index.js):
import React from "react"
import { StaticQuery, GraphQL, Link } from "gatsby"
import Layout from "../components/layout"
import Image from "../components/image"
import SEO from "../components/seo"
const IndexPage = () => (
<Layout>
<StaticQuery query={GraphQL`{
allWordpressPage {
edges {
node {
id
title
content
}
}
}
}`} render={props => (
<div> {props.allWordpressPage.edges.map(page => (
<div key={page.node.id}>
<h1>
{page.node.title}
</h1>
<div dangerouslySetInnerHTML={{__html: page.node.content}} />
</div>
))}
</div>
)}
/>
</Layout>
)
export default IndexPage
The error and warnings that show in browser:
TypeError: Object(...) is not a function
IndexPage
src/pages/index.js:1
> 1 | import React from "react"
2 | import { Link } from "gatsby"
3 |
4 | import Layout from "../components/layout"
View compiled
▶ 17 stack frames were collapsed.
JSONStore._this.handleMittEvent
/Users/kennansmith/Desktop/Temp_Task_Folder/gatsby-wp/.cache/json-store.js:1
> 1 | import React from "react"
2 |
3 | import PageRenderer from "./page-renderer"
4 | import normalizePagePath from "./normalize-page-path"
View compiled
▶ 2 stack frames were collapsed.
r.<anonymous>
/Users/kennansmith/Desktop/Temp_Task_Folder/gatsby-wp/.cache/socketIo.js:20
17 | // Try to initialize web socket if we didn't do it already
18 | try {
19 | // eslint-disable-next-line no-undef
> 20 | socket = io()
21 |
22 | const didDataChange = (msg, queryData) => {
23 | const id =
View compiled
▶ 24 stack frames were collapsed.
Maybe these imports are not the default ones?
import Layout from "../components/layout"
import Image from "../components/image"
import SEO from "../components/seo"
check if they ere exported as default, otherwise you shuld use {} import
Ok, got it working again.
The issue was that I was using GraphQL instead of graphql. The case-sensitivity was throwing the whole thing off. Replacing both instances of GraphQL with graphql fixed the issue and now I am seeing my data rendered on the page as intended.

Importing an image into an <src> tag in React.js when the image name is not known in advance

I have a component in React which displays (or doesn't at the moment) an image within an src tag.
The file path & file name of the image is passed via props after being selected by the user, so I can't do an import at the top of the file. Apparently, I should be able to do something like src={require(file)} but this causes webpack to throw a hissy fit and give the following error: Error: cannot find module "."
As an e.g., a typical filepath/filename I pass to the component is: '../../../images/black.jpg'
This is a stripped-down version of the code in question:
import React, { Component } from "react";
class DisplayMedia extends Component {
render() {
return (
<div className="imgPreview">
<img src={this.props.file} alt="piccy" />
</div>
);
}
}
export default DisplayMedia;
Depending on your set up...
If the images are dynamic (during production, images will be added, edited, or deleted):
I'd recommend a microservice that only handles images. I go in depth on how to approach such a service: Image returned from REST API always displays broken
If the images are static (during production, the images are bundled within the "bundle.js" file):
- I'd recommend importing all of the images within the component, creating an array of the imported images, and then utilizing the array index and React state to cycle through them. For example:
import React, { Component } from "react";
import Image1 from "../images/Image1.png";
import Image2 from "../images/Image2.png";
import Image3 from "../images/Image3.png";
const images = [Image1, Image2, Image3];
export default class ShowImage extends Component {
state = { index: 0 };
handleChange = ({ target: { value } }) => {
this.setState({ index: value });
};
render = () => (
<div className="container">
<h1>Utilizing Array Indexes</h1>
<select
style={{ marginBottom: 20 }}
value={this.state.index}
onChange={this.handleChange}
>
{images.map((val,idx) => (
<option key={idx} value={idx}>Image {idx + 1}</option>
))}
</select>
<img src={images[this.state.index]} />
</div>
);
}
While I can't create an exact codesandbox of the above, this working example should give you the basic idea: https://codesandbox.io/s/ovoo077685
You don't need to add require in src. When relative path is used it will go the images availale in your server but when url is given image will be loaded. You can find more info here
When using src as /images/black.jpg it will convert to localhost:3000/images/black.jpg

Resources