I used create-react-app to play with react. I noticed that no matter what I type in after localhost:3000/ (which is the default url on dev machine) I always get the content from localhost:3000
This means I cannot access images so that sort of means I can't really do anything with it.
Is this a bug or is it some awesome new feature that I just don't understand? How can this be switched off?
Create React App uses historyApiFallback for the webpack-dev-server, which means that all requests that give a 404 response will fall back to load the index.html file.
If you e.g. add an image to the public folder, you can see that the image takes precedence over the index.html file.
You can also import the image with the help of Webpack and use the import as src in your code, and Webpack will make sure the image ends up in the final build folder for you.
import img from './image.png';
you can use
render() {
return <img src={process.env.PUBLIC_URL + '/img/logo.png'} />;
}
for more information please refer Adding Assets Outside of the Module System
Related
I deployed my react app to gh-pages and my images arent loading anymore. They are held in the public folder and I am loading the them using the react-three-fiber hook useLoader according to their documentation like this:
const [theImage, 2ndImage] = useLoader(TextureLoader, [
"/{folderName}/{the-image}.jpeg",
".../etc",
])
Also Ive tried directing to the image using process.env.PUBLIC_URL + "/{folderName}/{the-image}.jpeg"
Gh-pages documentation says best practice is to load the image with the relative path and not the absolute path. But still my page cant seem to access them.
My Console error reads:
Uncaught Error: Could not load /{myrepo}{folderName}/{the-image}.jpeg: undefined)
at index-6f0019d1.esm.js:1670:1
Ive seen other post on this issue like this one but I dont quite understand the answer marked as correct. Can anyone explain?
I setup a new Gatsby project through the installer but when I try to create a new file in /src/pages, but if then I go to that route, the browser says
Preparing requested page
in loop. In the browser console it outputs:
[Error] Unhandled Promise Rejection: Error: We couldn't find the correct component chunk with the name "component---src-pages-home-js" (anonymous function) (loader.js:45) promiseReactionJob
This is my home.js (in a normal React environment works perfectly):
import React from "react";
const Home = () => {
return (
<div>
<title>Test</title>
<p>Hello</p>
</div>
);
};
export default Home;
Project structure:
pages
- 404.js
- index.js
- second.js
What could be the problem? I already tried to reinstall Gatsby again and tried cleaning caches or making another file, with a different file names. The file is seen by Gatsby because if I try to access the route without creating the file, it gives me the 404 page.
Thanks.
UPDATE:
If you're using a Mac with M1 Chip, make sure you installed Gatsby with Rosetta!
Also hit the same problem with M1 MacBook Air when adding pages to Gatsby sample project. The solution (found elsewhere) was to empty the browser cache.
Have you tried renaming your home.js to index.js?
After that, clean the cache by gatsby clean.
This may be due to data in your browser cache. Clear the cache in Safari with Option + Command + E
Clearing browser caché was the solution for mee too, as #JohnysSon says
yesterday I wanted to create a landingpage for a subcategory if my website. The site it build with create react app. I created the sub-page using react router. On lokal machine everything works fine.
But after I deployed it on AWS (amplify) the included fonts in the whole app (old site and new one) are not working anymore.
I am getting the "Failed to decode downloaded font: " and "OTS parsing error: invalid version tag" errors.
I didn't changes anything in the index.scss/index.html files.
After I`m running the build command the fonts-files are in the right folder ...
This is how my index.scss looks like:
#font-face {
font-family: "SF Compact Display";
src: url("./assets/fonts/SF-Compact-Display-Regular.otf");
}
#font-face {
font-family: "SF Compact Display Semi";
src: url("./assets/fonts/SF-Compact-Display-Semibold.otf");
}
I also tried it with absolute path :
enter code here src: url("assets/fonts/SF-Compact-Display-Semibold.otf");
But it doesn't work.
I imported the index.scss into my index.tsx import './index.scss'
Both files are living in the src root.
I have read lots of other stories that are similar to my problem. But nothing works.
Does anyone have a guess why I am getting this problem? Is there maybe a redirecting issue with aws as this is the only think which I changed?
(as i said before I included the react router the fonts where working fine ). I also tried to remove the react router and get the old page with the right fonts. But now I have the same issue there.
On aws rewrites I included </^[^.]+$|\.(?!(css|gif|ico|json|jpg|js|png|txt|svg|woff|ttf|otf)$)([^.]+$)/> with /index.html and 200 Rewrite.
Im trying to fix it for hours now, but I don't have any clue what the issue could be.
I hope anyone had the same issue in the past and can help me.
Bests
Not sure if you already solved this, but here're some thoughts to help.
The Failed to decode downloaded font error is almost certainly because the app responded to the browser's request for the font with html. This would likely happen if there's a catch-all route configured for the SPA (e.g. respond with the root index page or a not-found page).
From the info you've shared, the most likely issue is that the relative path to the font files is being broken in the build process. The key insight here is that url("assets/fonts/SF-Compact-Display-Semibold.otf"); isn't actually an absolute path because it's missing the / prefix. If your build's putting the font file in /assets/fonts/SF-Compact-Display-Semibold.otf, what you want is: url("/assets/fonts/SF-Compact-Display-Semibold.otf");.
A useful way to check the directory structure produced by building is to run npm run build (see https://create-react-app.dev/docs/production-build/). This produces a production build in a directory called build. When creating an AWS Amplify project, it automatically sets up running the build process for you (see https://docs.aws.amazon.com/amplify/latest/userguide/build-settings.html). By default, for create react app apps, this means it'll do npm run build prior to deploy.
I've created a simple React app using npx create-react-app react-portfolio
Created simple page, all things are working properly on my local machine
Pushed to GitHub and published my portfolio into gh-pages (https://yanalinso.github.io/react-portfolio/) and it works!
I changed PCs, and cloned the same code from my repository (https://github.com/yanalinso/react-portfolio)
run npm install and npm start on my local machine, the images does not work anymore (logo and the background picture), but the CSS is working
https://ibb.co/4NchQJG (Result on my local machine)
https://ibb.co/RQVv6KB (Chrome console)
https://ibb.co/ZGN1cPd (File tree, same as with my other machine)
https://ibb.co/qmfwX44 (cmd run result)
My code is simple to use images
img src="img/logo1.png"
I can still push changes on GitHub page and it's working fine,
though images are not working on my local machine.
You need to import it first like this to tell webpack that JS file is using this image
import logo1 from './img/logo1.png';
and then this:
<img src={logo1} />
I tried changing to other picture but still failed,
SOLUTION!
I've restored the package.json to default, so i've removed the config of gh-page on script and removed homepage == IT WORKS!!
Thanks guys for helping :)
I have been searching around regarding this and I find this very strange. I'm a beginner and the solution I can only come back with is
import ANYNAME from "path of file e.g ../images/logo1.png".
import ANYNAME from "../images/logo1.png"
Take note ../ is to reference a file outside the folder you are in.
If in the same folder use ./
Then when you are to use it
<img src={ANYNAME}/>
rather than <img src="../images/logo1.png"/> // This line doesn't work
I have a React page made with create-react-app and I deployed it to github pages per the instructions here. It opens, but the resources on the public directory aren't being loaded. What seems to be happening is that during the page load, http://{name}.github.io/{repo} is being truncated to http://{name}.github.io, and so the relative path to the public directory is no longer correct at the point when the page attempts to load them. If I try to then reload the page with the url http://{name}.github.io I get a 404 error.
I could just alter the paths to make it work, but that feels like a hack. I want to know what's going on here and how I might fix it, if that's possible.
The code can be seen here: https://github.com/CBreakr/ATTCK_StarWars
Supplement to the answer: https://medium.com/#svinkle/how-to-deploy-a-react-app-to-a-subdirectory-f694d46427c1
It's a bit difficult to say without seeing your code.
However it's likely that your react-router is not setup properly.
You should setup your router like this:
import { BrowserRouter as Router } from ‘react-router-dom’;
const routerBaseName = process.env.PUBLIC_URL;
ReactDOM.render(<Router basename={routerBaseName}>< App /></Router>, document.getElementById(‘root’));
Note the basename part - it should be set to your production url when you build the bundle (in this case: https://CBreakr.github.io/ATTCK_StarWars/)
it should be set to your localhost url when you are developing locally.
You can use .env files to set values for PUBLIC_URL (I believe with create-react-app you will have to change it to REACT_APP_PUBLIC_URL) for dev/prod environments respectively, see: https://create-react-app.dev/docs/adding-custom-environment-variables
You need the homepage defined in package.json
"homepage": "http://gitname.github.io/react-gh-pages"
https://github.com/gitname/react-gh-pages#procedure
https://create-react-app.dev/docs/deployment#serving-the-same-build-from-different-paths. Setting your homepage this way may help "homepage": ".".
Also there is another tutorial in the same page you may want to check that as well https://create-react-app.dev/docs/deployment#github-pages-https-pagesgithubcom
Try to wrap your Switch Component inside HashRouter like this
import { HashRouter} from "react-router-dom";
<HashRouter basename="/">
<Switch>
//...
</Switch>
</HashRouter>
The only concerning difference I found, in your codebase - is the homepage in package.json is not HTTPS.
Current settings -
"homepage": "http://CBreakr.github.io/ATTCK_StarWars",
Change to -
"homepage": "https://CBreakr.github.io/ATTCK_StarWars",
It's good that your repo has a gh-pages branch that contains your build directory contents. Please make sure the repository deployment settings use gh-pages branch.
EDIT -
UPDATED ANSWER
The URL attribute is wrongly configured for your <img> tags. The possible values for the attribute are:
Absolute image path - src="http://www.example.com/image.gif"
Relative image path - src="image.gif"
Note: If you notice that character images are not loading but the movie posters for a character are loading fine, the reason being - the posters have absolute image path e.g. Revenge of the Sith has image source as -
https://vignette.wikia.nocookie.net/starwars/images/e/e7/EPIII_RotS_poster.png/)
But character images are configured like src='/images/vader.jpg'.
You could solve this by changing src of your static images in characters.json from -
"imageURL": "/images/vader.jpg"
to:
"imageURL": "images/vader.jpg"
OR
"imageURL": "./images/vader.jpg"
You can check the validity of this solution by inspecting the image of your Vader character component here. Update the image tag source and see that the character images now load properly.