How to import GIF in NextJS - javascript

I'm trying to prepare my portfolio website with Nextjs. I want to use gif in the site. You can find my code below. I could not find how to do it.

Next/Image does support GIF files...my first thought would be to ask if you have explicitly whitelisted a set of external domains in your next.config.js file? For the Next/Image Loader to handle external domains they must be individually whitelisted. Here are the contents of my next.config.js file.
const path = require('path');
const withBundleAnalyzer = require('#next/bundle-analyzer')({
enabled: !!process.env.ANALYZE
});
module.exports = withBundleAnalyzer({
webpack(
config,
{
dev = process.env.NODE_ENV === 'development',
isServer = typeof window === 'undefined'
}
) {
if (isServer) {
require('./scripts/generate-sitemap');
}
/**
* !dev ? preact/compat : react, react-dom on build
* reduce page weight in production by ~10%
*/
if (!dev && !isServer) {
Object.assign(
(config.resolve.alias['#/'] = path.resolve('./')),
{
react: 'preact/compat',
'react-dom': 'preact/compat'
}
);
}
return config;
},
sourceMaps: {
productionBrowserSourceMaps: true
},
images: {
domains: [
'avatars.githubusercontent.com',
'faderoom-headless.us',
'www.faderoom-headless.us',
'dtmqnbkq3btfh.cloudfront.net',
'secure.gravatar.com',
'automattic.com',
'serve.onegraph.com',
'onegraph.com',
'maps.google.com',
'lh3.googleusercontent.com',
'maps.gstatic.com',
'thefaderoom146.booksy.com',
'dev-3cqt2bq0.auth0.com',
'scontent-sea1-1.xx.fbcdn.net',
'd2zdpiztbgorvt.cloudfront.net',
'platform-lookaside.fbsbx.com',
'square-postoffice-production.s3.amazonaws.com'
]
},
future: {
webpack5: true,
strictPostcssConfiguration: true
},
i18n: {
locales: ['en-US'],
defaultLocale: 'en-US'
}
});
console.log(
'next.config.js',
JSON.stringify(module.exports, null, 2)
);
So you would have to whitelist media.giphy.com and it should work just fine. I also do recommend setting the quality prop for the Image component. Quality defaults to 75 out of 100 but I'd suggest making that closer to 100 for better UX.

Next/Image now supports gifs.
You should be able to import the gif and then toss it into the src like this
import Image from 'next/image';
import myGif from 'url'
...
<Image src={myGif} alt="my gif" height={500} width={500} />
If the url doesn't work here, it should work if you download the gif and toss it into assets.

At first I entered your code:
Your code
and nextjs gave me this as an error:
Screenshot erreur
So I added the domain 'media.giphy.com' in the configuration 'next.config.js'
This file must be added to the root of the project, at the same level as the 'pages' or 'lib' folder for example and must be called 'next.config.js':
File place screenshot
And in it you have to put this:
module.exports = {
images: {
domains: ['media.giphy.com']
}
};
Then you have to restart your next js server.
And normally you get this:
Image Screenshot
Here is some documentation to read to better understand:
https://nextjs.org/docs/basic-features/image-optimization

You can also use the prop unoptimized to serve the image as it is:
make sure you white list your domain in the next.config.js
module.exports = {
images: {
domains: ['SOURCE_IMAGE_DOMAIN']
}
};
then in your image component:
import Image from 'next/image';
<Image unoptimized={true} src={GIF} alt="the gif" height={500} width={500} />
Next documentation:
https://nextjs.org/docs/api-reference/next/image#animated-images

Related

Configure Next Js For Images For External Domains [duplicate]

This question already has answers here:
how to add domains to next.config.js for "next/image" while using a plugin
(2 answers)
Closed 10 months ago.
I'm having an issue with next.config.js. I'm currently running a project with next js on typescript. In this project i am working with ThreeJs, #react-three/fiber & #react-three/drei. But I also want to include some images from a specific public YouTube url.
In older projects i have implemented this withought having ThreeJs inside like this:
module.exports = {
reactStrictMode: true,
images: {
domains: ['i3.ytimg.com', 'img.youtube.com'],
formats: ['image/webp'],
},
}
That being on my next.config.js and it still works like a charm. But when I put it in my current project and try to load an image I get error saying:
Error: Invalid src prop ([url]) on next/image, hostname "img.youtube.com" is not configured under images in your next.config.js
Current next.config.js file
module.exports = {
reactStrictMode: true,
images: {
domains: ['i3.ytimg.com', 'img.youtube.com'],
formats: ['image/webp'],
},
}
const withTM = require('next-transpile-modules')(['three', '#react-three/fiber', '#react-three/drei']);
module.exports = withTM();
On my component now:
export default function ProjectCard({ song }: { song: Lyrics }) {
const img = hqDefault(song.thumbnailURL);
return (
<div>
{song.singer}
<Image src={img} alt={`${song.singer} ${song.title}`} layout="fill" />
</div>
)
}
hqDefault Function:
export const hqDefault = (url: string): string => {
return `https://img.youtube.com/vi/${url}/hqdefault.jpg`;
}
Any help will be appriciated!
You are supposed to export a single configuration object.
First, Install 'next-compose-plugins':
npm install --save next-compose-plugins
Import it:
const withPlugins = require('next-compose-plugins');
And then export your config like this:
module.exports = withPlugins([
[withTM]
], nextConfig);

Nuxt image keeps breaking on page change

I have image displayed on my Nuxt page but anytime I navigate away from it back the image breaks and I do not know why.
I have this in my code
<img :src="baseUrl + 'storage/'+ front.featured_image" alt="post-title" />
and my script
data: () => ({
frontpage: [],
baseUrl: process.env.BASE_URL
}),
async asyncData({ $axios }) {
const response = await $axios.get('/api/frontpage')
return { frontpage: response.data.posts }
},
I have a .env file and I have the following inside it BASE_URL=http://localhost/ and I also have the following inside nuxt.config.js
env:{
baseUrl: process.env.BASE_URL || 'http://localhost/'
}
My API is built using laravel and it is loading from http://localhost/ but Nuxt keeps going back to localhost:3000 on page change.
You can check my previous answer here: https://stackoverflow.com/a/67705541/8816585
This may help
export default {
publicRuntimeConfig: {
baseUrl: process.env.BASE_URL,
},
}
Otherwise, this configuration of Axios may also help!

Is it possible to import image file dynamically in Nuxt js with env?

// env.development.js
module.exports = {
fileName: 'banner_dev.png'
}
// env.production.js
module.exports = {
fileName: 'banner_prod.png'
}
// index.vue
<script>
import bannerSrc from '#/assets/img/' + process.env.fileName
export default {
data () {
return {
banner: {
src: bannerSrc,
}
}
},
</script>
Hello, I'm new to Nuxt js.
I would like to import an image file dynamically with using env value when build it.
However, I get error at below.
import bannerSrc from '#/assets/img/' + process.env.fileName
Is it possible to import image file dynamically with using env file?
If possible is there work around for it?
Thanks!
Yes you can.
Follow these steps:
1 - define your var in a .env file:
IMAGE=lama
2 - Add the environment var in your nuxt.config.js file:
{
publicRuntimeConfig: {
image: process.env.IMAGE
},
}
3 - Call it in a vue.js file:
<img
:src="require(`~/assets/images/${$config.image}.jpg`)"
style="width: 250px; height: 200px"
/>
Here is a codesand box:
https://codesandbox.io/s/nuxtjs-load-image-dynamically-with-environment-variable-e3xgf
Have fun! :)

How do I solve Error importing a css file with next.js?

Error:
./node_modules/quill-emoji/dist/quill-emoji.css
ModuleParseError: Module parse failed: Unexpected character '�' (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
(Source code omitted for this binary file)
In _app.js, I have:
import "quill-emoji/dist/quill-emoji.css";
And in next.config.js:
const withCSS = require('#zeit/next-css');
const withImages = require("next-images");
const withPlugins = require("next-compose-plugins");
if (typeof require !== 'undefined') {
require.extensions['.less'] = () => {};
require.extensions['.css'] = file => {};
}
module.exports = withPlugins([
withImages,
withCSS
], {
devIndicators: {
autoPrerender: false,
},
webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
...
})
The emoji css seems to include content of data:image and loads svg's inline.
I was trying with multiple loaders and couldn't find the right sequence, you probably need resolve-url-loader in some specific sequence.
It maybe best to just link it using next/head and call it a day.
I think the emoji icons are svg. You might need an svg loader to solve this problem.
next-images adds support for jpg, jpeg, svg, png, ico, webp and gif images.
NOTE: I have not tested this with quill
This is an example snippet.
const withImages = require("next-images");
module.exports = withImages({
webpack(config, options) {
return config;
}
});

.env Nuxt JS doesn't resolve routes in generate option correctly

I'm trying to use Nuxt JS's 2.9.2 generate object to generate dynamic pages as static files using my .env file to pull a URL, I'm having difficuility in getting it to properly link up:
nuxt.config.js
require('dotenv').config();
import pkg from './package'
import axios from 'axios'
export default {
mode: 'universal',
env: {
blog_api: process.env.BLOG_API || "http://localhost:3000/articles/blogs.json"
},
/*
** Build directory
*/
generate: {
dir: 'dist-next',
routes: function () {
return axios.get(`${process.env.blog_api}`)
.then((res) => {
return res.data.blogs.map((blog) => {
return '/posts/view/' + blog.title
})
})
}
}
}
The above code, more specifically ${process.env.blog_api}, can't seem to resolve the routes, despite it working perfectly if I replace it with my own local domain.
.env
BLOG_API="http://my-local-domain.clone/articles/blogs.json"
EDIT:
Updated code with my config, http://my-local-domain.clone/articles/blogs.json is inside of static/articles
You should use dotenv module:
https://www.npmjs.com/package/dotenv
More Info about configuration with NUXT you have here:
https://samuelcoe.com/blog/nuxt-dotenv/
You probably want to set your env property in nuxt.config.js, for example:
module.exports = {
env: {
BLOG_API: process.env.BLOG_API_URL,
},
In your component, you can now use them :
makeAsyncCall({
to: process.env.BLOG_API,
})

Categories