-
Notifications
You must be signed in to change notification settings - Fork 74
v1 Images
The simplest way to include images in your client code is by importing them, and using the resulting path as the src
:
import myImg from "path/to/some/image.png";
export default function SomeComponent() {
return <img src={myImg} />;
}
Images handled in this way (e.g. client/src/pages/logo.svg
) are bundled by Webpack and included in dist/static/
along with all of the other client-side assets when you npm run build
.
This loading is configured in client/webpack/common.config.js
, where you can update the test
regex to include other kinds of image (e.g. .webp
):
{
test: /\.(png|svg|jpe?g|gif)$/,
loader: "file-loader",
},
If you'd like to serve images directly from the server instead, you can use Express's own static
middleware. For example, if you create a new directory server/images/
containing your images, you can add the following to server/app.js
:
import { join } from "node:path";
// ...
app.use("/images", express.static(join(__dirname, "images")));
Now you can use a relative path to the image just like the API routes:
export default function SomeComponent() {
return <img src="/images/image.png" />;
}
In this case you should also add "/images"
to the list of routes that are proxied in development mode, see client/webpack/dev.config.js
:
proxy: [
{
- context: ["/api"],
+ context: ["/api", "/images"],
logLevel: "debug",
logProvider: () => console,
target: "http://localhost:3100",
},
],
However note there is no particular performance improvement here; the images import
ed in the client code are also served statically by Express in production mode, via the existing clientRouter
defined in server/utils/middleware.js
.