问题
How to show images? It can not be shown correctly below.
In the src/components/Header.js
file:
<img src="../images/logo.png" style={{width:"112",height:"28"}} />
回答1:
Importing Assets Directly Into Files
import React from "react" import logo from "./logo.png" // Tell Webpack this JS file uses this image console.log(logo) // /logo.84287d09.png function Header() { // Import result is the URL of your image return <img src={logo} alt="Logo" /> } export default Header
The reason this is best is that it enables optimizations through the Webpack bundling pipeline, e.g. compression, data URLs, cache busting filename hashes, etc.
Using the Static folder
This is mostly useful for files other than images.
You can create a folder named
static
at the root of your project. Every file you put into that folder will be copied into thepublic
folder. E.g. if you add a file namedsun.jpg
to thestatic
folder, it’ll be copied topublic/sun.jpg
You can reference assets from the static folder in your code without anything special required:
render() { // Note: this is an escape hatch and should be used sparingly! // Normally we recommend using `import` for getting asset URLs // as described in the “Importing Assets Directly Into Files” page. return <img src={'logo.png'} alt="Logo" />; }
Corey's answer quotes the "Add custom webpack config" section of the Gatsby documentation, which is useful but unnecessary to load images.
回答2:
Create a gatsby-node.js
file at the root of your project if you don't already have one and add this:
const path = require("path")
exports.onCreateWebpackConfig = ({ stage, actions }) => {
actions.setWebpackConfig({
resolve: {
modules: [path.resolve(__dirname, "src"), "node_modules"],
alias: { react: path.resolve("./node_modules/react") },
},
})
}
This does two things:
- It will make
src
the base for your imports - It will ensure that you don't run into weird bugs due to multiple versions of React getting loaded (plugins that need to reference React can cause this).
In your Header.js file, you can now do this:
import logo from "images/logo.png"
export const Header =>
<header>
<img src={logo} alt="Logo Alt Text" />
</header>
The rendered result of this will actually be different depending on the file size of your logo. If it's small enough, Gatsby will inline it using base64, reducing the number of HTTP requests required to load your page. If it's larger, it will be given an asset fingerprint and added to the assets available when your site is built and the URL to the file will be used for the src
attribute (e.g. /images/logo-123asd.png
). This will allow you to use HTTP cache headers that tell the browser it's safe to cache this file for a long time; if it changes, the URL will change and you don't need to worry about invalidating the cached version.
来源:https://stackoverflow.com/questions/56955191/how-to-show-images-in-a-gatsbyjs-project