How to export static images on Nextjs? - javascript

when I want to export my nextjs app, it says that I cannot export my images on static websites.
Error: Image Optimization using Next.js' default loader is not compatible with next export.
Possible solutions:
- Use next start to run a server, which includes the Image Optimization API.
- Use any provider which supports Image Optimization (like Vercel).
- Configure a third-party loader in next.config.js.
- Use the loader prop for next/image.
How can I make it so that it does ?
Is there a way for me to simply tell it to render images statically ? I dont want to go throught other onlines images loaders..

I created a npm module so that we can use the Next.js <Image/> component with optimized images while using the static export functionality.
https://www.npmjs.com/package/next-image-export-optimizer
The library wraps the <Image /> component of Next.js and automatically creates optimized images using sharp.js at export time.
It uses a custom loader to create a srcset for the <img /> that the <Image /> component of Next.js creates. Then at build/export time, the images inside the public/images folder (as an example) are optimized with sharp.js and copied into the build folder.

You need to set up a custom image loader in Next.js
In your next.config.js file, add this property to the export:
images: {
loader: "custom"
}
And make a script called loader.js that exports this:
function imageLoader({ src }) {
return `/images/${src}`; // REPLACE WITH YOUR IMAGE DIRECTORY
}
module.exports = imageLoader;
For each Image component, set the loader prop manually:
const imageLoader = require("PATH TO loader.js");
<Image loader={imageLoader} />

I'm going to add onto skara9's answer because it didn't quite work for me. I found a thread on github discussing it and the answer there worked for me. It just wraps around the NextJS image component and works pretty flawlessly for me.
// components/Image.js
import NextImage from "next/image";
// opt-out of image optimization, no-op
const customLoader = ({ src }) => {
return src
}
export default function Image(props) {
return (
<NextImage
{...props}
loader={customLoader}
/>
);
}
Make sure you change your imports and update your next.config.js
import Image from '../components/Image.js'

Related

How to add custom scripts bundle in NextJS

I have some legacy custom javascripts that I need to bundle and put them in _document.js as a link. The filename should include a hash.
What would be the best way to accomplish this?
I tried webpack configs regarding entry/output but they break NextJs build.
The problem is that we use things like window, document, etc that do crash in server side.
Ideally what is needed is to inject this into a tag, as compiled / babelified javascript code.
What I tried is
Webpack HTML Plugin plus other plugins like InlineChunk or
InlineSource plugins. They didn't work because they generate code in
an index.html that is not used by NextJS.
Using Raw Loader to get the file content. Doesn't work because it is
not babelified.
Adding a custom entry to the Webpack config, like scripts:
'path/to/my-entry.js'. Didn't work because it adds a hash name to the
file and I have no way of knowing it.
Adding a custom entry into the NextJs polyfills. I thought it made
sense, but the polyfill tag has a nomodule which prevents its code to
run on new browsers.
Another options is to add the javascript code as a string, and then using __dangerouslySetInnerHtml but the problem is that I lose linter and babel abilities there.
I tried adding it as a page, but crashes for local development and even on build
webpack.config.js
module.exports = (nextConfig = {}) =>
Object.assign({}, nextConfig, {
webpack(config, options) {
const nextJsEntries = config.entry;
config.entry = async () => {
const entries = await nextJsEntries();
entries['pages/rscripts'] = 'test/test.js';
return entries;
};
...
Then in _document.js
<script src={`${publicRuntimeConfig.ASSET_PREFIX}/_next/${this.props.buildManifest.pages['/rscripts'][2]}`} />
You can just import js file like import 'path/to/js_file' in your _app.js/app.tsx file
import "../styles/globals.css"
import "../js/test"
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}
export default MyApp
This one works fine for me
I wanted to add another answer here as I came across this and I believe some things have changed in Next JS. Next now has this script component that you can use to load external scripts or dangerously set a script.
The Next.js Script component, next/script, is an extension of the HTML
element. It enables developers to set the loading priority of
third-party scripts anywhere in their application, outside next/head,
saving developer time while improving loading performance.
The cool thing is you can put them into whatever pages you want, maybe you have a script you want on a homepage, but not other pages, and Next will extract them and place them on the page based on the strategy you select. There are a few gotchas, can't load in the head, beforeInteractive is a little finicky, so I would read the link above and the actual API reference before making any choices.
import { useEffect } from 'react';
import Script from 'next/script';
function thirdPartyScript() {
useEffect(() => {
// just for fun. This actually fires
// before the onLoad callback
}, []);
return (
<Script
id="test-script"
strategy="afterInteractive"
src="/public/pages/scripts/test.js"
onLoad={() => {
console.log('Onload fires as you would expect');
}}
/>
);
}

Gatsby Would Seem to Require an 10x the Effort of Any Other Framework to Add One Image: What Am I Not Understanding?

This is the code for a single image in any other Javascript framework in existence:
<img src="images/someFile.png" />
... possibly with some styling.
This is the code for a single image in Gatsby (basically copied from the Gatsby Image documentation page, https://www.gatsbyjs.org/docs/gatsby-image/ ... and this is just a simple example):
import { useStaticQuery, graphql } from "gatsby"
import Img from "gatsby-image"
export default function Image() {
const data = useStaticQuery(graphql`
query {
file(relativePath: { eq: "images/someFile.png" }) {
childImageSharp {
fixed {
...GatsbyImageSharpFixed
}
}
}
}
`)
return (
<Img fixed={data.file.childImageSharp.fixed} />
)
}
Holy hell, I'm supposed to write all that code (ok, I don't have to repeat the imports, but still) for every image in my site?!?
That can't be right, so clearly I'm not understanding something. Can someone please clarify what I'm not getting about Gatsby?
If it truly takes that much code to just to add one image to a site, Gatsby must be the slowest framework ever to develop in (but from it's popularity I can't believe that's true). Or do most Gatsby sites just use very few images?
See Importing Assets Directly Into Files and Using the Static Folder
import React from "react"
import importedImage from "../images/gatsby-icon.png"
const IndexPage = () => (
<>
<img src={importedImage} alt="Description of my imported image" />
<img
src="staticfolderimage.jpeg"
alt="Description of my image in the ./static folder"
/>
</>
)
export default IndexPage
At the very start of the page which you mention there is a bit of explanation
gatsby-image is a React component designed to work
seamlessly with Gatsby’s native image processing capabilities powered
by GraphQL and gatsby-plugin-sharp to easily and completely optimize
image loading for your sites.
gatsby-plugin-sharp can compress jpeg/png images
Holy hell, I'm supposed to write all that code (ok, I don't have to
repeat the imports, but still) for every image in my site?!?
I think you can extract some things as params like eq: "images/someFile.png" and make it reusable
Example
import { useStaticQuery, graphql } from "gatsby"
import Img from "gatsby-image"
export default function Image({source}) {
const { file: {childImageSharp: {fixed} } } = graphql(`
query($source: String!) {
file(relativePath: { eq: $source }) {
childImageSharp {
fixed {
...GatsbyImageSharpFixed
}
}
}
}
`, {source})
return <Img fixed={fixed} />
}
It's a nice topic to discuss and share. It's always up to you to use a <img> tag (importing assets directly in the component) or <Img> React's Component from Gatsby, adding and extending all support it has. From Gatsby Image documentation:
gatsby-image is a React component specially designed to work
seamlessly with Gatsby’s GraphQL queries. It combines Gatsby’s native
image processing capabilities with advanced image loading techniques
to easily and completely optimize image loading for your sites.
gatsby-image uses gatsby-plugin-sharp to power its image
transformations.
Note: gatsby-image is not a drop-in replacement for <img />. It’s
optimized for fixed width/height images and images that stretch the
full-width of a container. Some ways you can use <img /> won’t work
with gatsby-image.
So, without going into detail of all the benefits of using <Img> from Gatsby (compression, lazy loading, fluid sizes, etc), it's not that hard to implement for every single image if you take into account a few details.
Gatsby is a CMS/data-sourced based framework so, by default, all data comes from a CMS or somewhere outsourced, meaning that it has to be queried via GraphQL. In those queries, ideally, you'll prepare your data, images included. That will avoid you to use the staticQuery you showed. For example, retrieving all images once you've set up your filesystem should look like:
{
allImageSharp {
edges {
node {
fluid(maxWidth: 800) {
...GatsbyImageSharpFluid
}
}
}
}
}
Note: this is an example query, the idea is to fetch and gather all data needed from an image to pass it to <Img> component
Then, in your component you simply need to:
//...other imports
import Img from "gatsby-image"
const yourComponent= ({ data }) => {
return <Layout>
{data.edges.map(({ node })=> <Img fluid={node.childImageSharp.fluid} />)}
</Layout>;
};
Gatsby's example from using <Img> maybe it's not the most accurate use-case to do it because it involves a staticQuery, another way of importing data that is not as usual as it seems. You can easily avoid it by using a standard GraphQL query, saving you a lot of lines of code.
What I'm trying to say is that if you set your data properly, using Gatsby's image it's almost like using the common HTML <img> tag.
The sample code you showed (from Gatsby's documentation) will always show the astronaut image, but of course, it's completely up to you to use a single <Img> component and remove the <Image> one or re-use it as you wish.

No response even if img path is specified on React APP

I Launch project with create-react-app. No response even if img path is specified on React APP.
Image is displayed when import statement is used
// not working (1)
<img src={"../img/hoge.png"} />;
//working (2)
import Hoge from "../img/hoge.png";
<img src={Hoge} />
I want to user pattern (1).
Please tell me the solution orz......
Use require for dynamic imports, path like "../img/hoge.png" is not available in runtime because Webpack generates data URI in build time.
import hoge from '../img/hoge.png'; // Tell webpack this JS file uses this image
console.log(hoge); // /hoge.84287d09.png
// For dynamic imports
<img src={require("../img/hoge.png")} />
See Adding images in CRA docs.
If you have a list of potential images at build time, you can use the dynamic import function to load them, although this will return a promise like so:
export class ImageLoader extends React.Component {
constructor(props: any){
super(props);
this.state = {
imagePath: undefined
};
}
render() {
if(this.state.imagePath)
return <img src={this.state.imagePath} />; // Render the image
import(/* webpackMode: "eager" */`../imgs/${this.props.imageName}.png`) // Bundle all paths of images into the bundle
.then((imagePath: string) => {
this.setState({ imagePath}); // Set the new state with the loaded image path
});
return null; // Don't render anything right now since the image hasn't loaded yet.
}
}
This will bundle ALL png images under the imgs directory, use a switch statement with all possible names if that is too much.
See Webpack Documentation and How does Dynamic Import in webpack works when used with an expression?

Conditionally import assets in create-react-app

Is it possible to conditionally import assets when creating a React app using create-react-app? I'm aware of the require syntax - example:
import React from "react";
const path = process.env.REACT_APP_TYPE === "app_1" ? "app_1" : "app_2";
const imagePath = require(`./assets/${path}/main.png`);
export default function Test() {
return (
<img src={imagePath} alt="" />
);
}
This however bundles all my assets no matter what.
It will load the proper image, but it will still bundle all the files together in the final build.
When I look in the dev tools for the final build, I can see all the assets there even though I only wanted to load the assets for app_1.
Am I forced to touch the webpack config, if so, what should I change? or is there another way?
In the days when React didn't exist we didn't put assets into our JS files. We let the CSS to decide, what assets to load for what selectors. Then you could simply switch a corresponding class on or off for a corresponding element (or even the whole page) and viola it changes color, background, or even a form. Pure magic!
Ah. What times these were!
All above is true and I do not understand why would anyone do or recommend doing it differently. However if you still want to do it (for any reason) - you can! Latest create-react-app comes with out-of-the-box support for lazy loading of arbitrary components via dynamic importing and code splitting. All you need to do is use parenthesized version of the import() statement instead of the regular one. import() takes in a request string as usual and returns a Promise. That's it. Source code of the dynamicaly requested component won't be bundled in, but instead stored in separate chunks to be loaded on demand.
Before:
import OtherComponent from './OtherComponent';
function MyComponent() {
return (
<div>
<OtherComponent />
</div>
);
}
After:
const OtherComponent = React.lazy(() => import('./OtherComponent'));
function MyComponent() {
return (
<div>
<OtherComponent />
</div>
);
}
Notice how function MyComponent part is identical.
For those wondering if it is tied to CRA or React, it's not. It's a generic concept that can be used in vanilla JavaScript.
You will need to use webpack (or other bundler.) The code is not being run when it's bundled, so the compiler has no way of knowing which branch of logic to follow (app_1 or app_2). Therefore you have to get into the bundler's logic in order to achieve your goal.
However, this isn't as scary as it seems since webpack has built in capability to do this (no 3rd parties required...)
I would look into using webpack.providePlugin
(https://webpack.js.org/plugins/provide-plugin)
or its sibling DefinePlugin
(https://webpack.js.org/plugins/define-plugin)
(I'm afraid these examples are off the top of my head, so it's very unlikely they'll work on first pass.)
Examples:
Both will require a provider module...
// in path/provider.js
module.exports = {
live: '/path/to/live/image',
dev: '/path/to/dev/image'
}
Provide Plugin Example
// in webpack
new webpack.ProvidePlugin({
imagePath: [
'path/provider', // the file defined above
process.env.ENVIRONMENT // either 'dev' or 'live'
]
}),
// in code
export default function Test() {
return (
<img src={imagePath} alt="" />
);
}
Define Plugin example:
// in webpack
new webpack.DefinePlugin({
'process.env.ENVIRONMENT': JSON.stringify(process.env.ENVIRONMENT)
});
// in code
var providers = require('path/provider'); // same path provider as above
export default function Test() {
return (
<img src={providers[process.env.ENVIRONMENT]} alt="" />
);
}
In both cases the bundler is forced to collapse your variable to an actual literal value at compile time - before bundling has taken place. Since you have now collapsed the logical path down to a single option, it is now free to only bundle the relevant assets.
You can't do this with default CRA settings.
Because if your dynamic require or dynamic import path is not static, webpack won't be able to determine which assets to include in the final build folder, therefore, it will grab everything from your ./src folder, and put them all to your build folder.
There is a way to do it with default CRA settings
You can add to .env something like
REACT_APP_SKIN=1
Put your skin assets in public/css1, public/css2 etc. And include them in public/index.html using code like
<link href="/css%REACT_APP_SKIN%/theme.css" rel="stylesheet">

react native use variable for image file

I know that to use a static image in react native you need to do a require to that image specifically, but I am trying to load a random image based on a number. For example I have 100 images called img1.png - img100.png in my directory. I am trying to figure out a way to do the following
<Image source={require(`./img${Math.floor(Math.random() * 100)}.png`)}/>
I know this intentionally does not work, but any workarounds would be greatly appreciated.
For anyone getting to know the react-native beast, this should help :)
I visited a couple of sites in the past too, but found it increasingly frustrating. Until I read this site here.
It's a different approach but it eventually does pay off in the end.
Basically, the best approach would be to load all your resources in one place.
Consider the following structure
app
|--img
|--image1.jpg
|--image2.jpg
|--profile
|--profile.png
|--comments.png
|--index.js
In index.js, you can do this:
const images = {
profile: {
profile: require('./profile/profile.png'),
comments: require('./profile/comments.png'),
},
image1: require('./image1.jpg'),
image2: require('./image2.jpg'),
};
export default images;
In your views, you have to import the images component like this:
import Images from './img/index';
render() {
<Image source={Images.profile.comments} />
}
Everybody has different means to an end, just pick the one that suits you best.
Da Man - Q: How is this answer using a variable?
Well, since require only accepts a literal string, you can't use variables, concatenated strings, etc. This is the next best thing. Yes, it still is a lot of work, but now you can do something resembling the OP's question:
render() {
var images = { test100: "image100" };
return (
<View>
<Text>
test {images["test" + "100"]}
</Text>
</View>
);
}
In JS require statements are resolved at bundle time (when the JS bundle is calculated). Therefore it's not supported to put variable expression as an argument for require.
In case of requiring resources it's even more trickier. When you have require('./someimage.png'), React Native packager will locale required image and it will be then bundled together with the app so that it can be used as a "static" resource when your app is running (in fact in dev mode it won't bundle the image with your app but instead the image will be served from the server, but this doesn't matter in your case).
If you want to use random image as a static resource you'd need to tell your app to bundle that image. You can do it in a few ways:
1) Add it as a static asset of your app, then reference to it with <Image src={{uri:'name_of_the_image_in_assets.png'}}/> (here is how you can add it to the native iOS app)
2) Require all the images upfront statically. Sth in a form of:
var randomImages = [
require('./image1.png'),
require('./image2.png'),
require('./image3.png'),
...
];
Then in your code you can do:
<Image src={randomImages[Math.floor(Math.random()*randomImages.length)]}/>
3) Use network image with <Image src={{uri:'http://i.imgur.com/random.jpg'}}/>
class ImageContainer extends Component {
this.state ={
image:require('default-img')
}
<View>
<Image source={this.state.image} />
</View>
}
In the context of this discussion,I had this case where wanted to dynamically assign images for a particular background. Here I change state like this
this.setState({
image:require('new-image')
})
I came to this thread looking for a way to add images in a dynamic way. I quickly found that passing in a variable to the Image -> require() was not working.
Thanks to DerpyNerd for getting me on the correct path.
After implementing the resources in one place I then found it easy to add the Images. But, I still needed a way to dynamically assign these images based on changing state in my application.
I created a function that would accept a string from a state value and would then return the Image that matched that string logically.
Setup
Image structure:
app
|--src
|--assets
|--images
|--logos
|--small_kl_logo.png
|--small_a1_logo.png
|--small_kc_logo.png
|--small_nv_logo.png
|--small_other_logo.png
|--index.js
|--SearchableList.js
In index.js, I have this:
const images = {
logos: {
kl: require('./logos/small_kl_logo.png'),
a1: require('./logos/small_a1_logo.png'),
kc: require('./logos/small_kc_logo.png'),
nv: require('./logos/small_nv_logo.png'),
other: require('./logos/small_other_logo.png'),
}
};
export default images;
In my SearchableList.js component, I then imported the Images component like this:
import Images from './assets/images';
I then created a new function imageSelect in my component:
imageSelect = network => {
if (network === null) {
return Images.logos.other;
}
const networkArray = {
'KL': Images.logos.kl,
'A1': Images.logos.a1,
'KC': Images.logos.kc,
'NV': Images.logos.nv,
'Other': Images.logos.other,
};
return networkArray[network];
};
Then in my components render function I call this new imageSelect function to dynamically assign the desired Image based on the value in the this.state.network:
render() {
<Image source={this.imageSelect(this.state.network)} />
}
Once again, thanks to DerpyNerd for getting me on the correct path. I hope this answer helps others. :)
Here is a simple and truly dynamic solution(no renaming or import required) to the problem if you have a bigger no of files.
[Won't work for Expo Managed]
Although the question is old I think this is the simpler solution and might be helpful. But I beg a pardon for any terminological mistakes, correct me please if I do any.
INSTEAD OF USING REQUIRE WE CAN USE THE URI WITH NATIVE APP ASSETS FOR ANDROID (AND/OR iOS). HERE WE WILL DISCUSS ABOUT ANDROID ONLY
URI can easily be manipulated as per the requirement but normally it's used for network/remote assets only but works for local and native assets too. Whereas require can not be used for dynamic file names and dirs
STEPS
Open android/app/src/main/assets folder from your App.js or index.js containing directory, if the assets folder doesn't exist create one.
Make a folder named images or any NAME of your choice inside assets, and paste all the images there.
Create a file named react-native.config.js in the main app folder containing App.js or index.js.
Add these lines to the new js file:
module.exports = {
project: {
ios: {},
android: {},
},
assets: ['./assets/YOUR_FOLDER_NAME/'],
};
at the place of YOUR_FOLDER_NAME use the newly created folder's name images or any given NAME
Now run npx react-native link in your terminal from main app folder, this will link/add the assets folder in the android bundle. Then rebuild the debug app.
From now on you can access all the files from inside android/app/src/main/assets in your react-native app.
For example:
<Image
style={styles.ImageStyle}
source={{ uri: 'asset:/YOUR_FOLDER_NAME/img' + Math.floor(Math.random() * 100) + '.png' }}
/>

Categories

Resources