twopluszero / next-images Goto Github PK
View Code? Open in Web Editor NEWImport images in Next.js (supports jpg, jpeg, svg, png and gif images)
License: MIT License
Import images in Next.js (supports jpg, jpeg, svg, png and gif images)
License: MIT License
I'm on NextJs 9.3.4 so I'm not using /static nor /public/static
steps to reproduce...
Failed to compile
./pages/index.jsx
Module not found: Can't resolve './test-image.jpg' in '/Users/home/projects/next-apps/project1/src/pages'
This could be the problem... if you look at the path above, it's resolving to the /pages sub-dir instead of the /public folder.
DO I NEED WEBPACK LOADERS??? Your docs did not say I needed it.
My main image keeps on fetching and I want to be able to cache it.
This is the header that i'm getting in dev tools - Cache-Control: public, max-age=0
Is there a way for me to chance the max-age?
I'm just wondering if you could share how this might be used to allow importing images within next-mdx-remote?
hello .my next.config file is
const withSass = require('@zeit/next-sass');
const withCSS = require('@zeit/next-css');
module.exports = withCSS(withSass());
I installed next-image and added it to config:
const withSass = require('@zeit/next-sass');
const withCSS = require('@zeit/next-css');
const withImages = require('next-images');
module.exports = withCSS(withSass());
module.exports = withImages();
but I got this error
./node_modules/react-modern-calendar-datepicker/lib/DatePicker.css 1:0
Module parse failed: Unexpected token (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
> .DatePicker {
| position: relative;
| display: inline-block;
how can I resolve this problem?
Is it possible to to set the webpack configurations so that multiple images with different sizes are created from one initial image. This would help to deliver the right sized image depending on screen sizes / resolutions.
If it's possible to do this within next-images, I would be happy if you could give me some hints how to implement this.
Thanks a lot!
When requiring images from pages/_document.js
the file is created by webpack, but next won't serve it. See the image below:
I also created a repo to reproduce that: https://github.com/felipero/next_images_bug
I have a Next.js app with CMS that can upload images, save images locally, and then display images on Next.js again.
I found that Next.js does not show images created at runtime, only images that exist at build time. So I tried this module.
static file serving
I first set up next.config.js
like this:
const withTM = require("next-transpile-modules")(["@fullcalendar"])
const withImages = require("next-images")
module.exports = withImages(
withTM({
async rewrites() {
return [
{
source: "/api/:slug*",
destination: "http://golang:5000/api/:slug*",
},
]
},
})
)
then I try to show my images with absolute url like this:
<img
className="d-block w-100"
src={require("/src/static" + url)}
/>
But it turns out not working, and shows An unexpected error has occurred..
Does anyone has any idea on why it does not work?
I have following next.config.js
:
const withCss = require('@zeit/next-css');
const withImages = require('next-images');
module.exports = withCss(withImages({}));
And this is the component:
import React from "react";
import Btn from "./Btn";
import Link from 'next/link';
import PNG from '../static/js.png';
import './Nav.css';
export default () => (
<nav>
<img src={PNG} className="logo" alt="Logo"/>
<Link href="/" passHref><Btn>Index</Btn></Link>
<Link href="/second" passHref><Btn>Second</Btn></Link>
</nav>
);
Here is what I get:
I would like to ask if version tags can be pushed for every release, as this project maintains no changelog file or GitHub releases. Having no git tags per version makes it hard to manually check the differences between releases.
If npm version
is used to update the NPM version, a git tag should also be created. This tag can be pushed with git push --tags
.
Thanks in advance!
Next.js implements custom build using to distDir
object in next.config.js.
Did you think to add in next-images?
Link: https://nextjs.org/docs#setting-a-custom-build-directory
It's possible to use next-images with SVG components (with https://github.com/airbnb/babel-plugin-inline-react-svg)? I tried but without success. When using both I'm not able to import SVG as a component, just as a URI. It's like next-images overridden it.
It seems like when importing an image using an absolute path from typescript, the code doesn't work.
For example, in my tsconfig file I have:
"paths": { "@components/*": ["src/components/*"], "@styles/*": ["src/assets/styles/*"], "@hooks/*": ["src/hooks/*"], "@images/*": ["src/assets/images/*"], }
Then on my component if I do something like
import Logo from '@images/logo.svg';
the code won't run, but does run fine if I do something like this:
import Logo from '../../../assets/images/logo.svg';
Hey there! I'm trying to setup next-images along with next-pwa, but for some reason whenever I try to put these two plugins together, the next-pwa breaks due to next-images.
I'm using next-compose-plugins to put then together, but I really have no idea why this is happening.
const withImageLoader = require('./webpack/image-loader');
const withCSS = require('@zeit/next-css');
const withPWA = require('next-pwa');
const withImages = require('next-images');
const withPlugins = require('next-compose-plugins');
// ... there is some code here
const { getBasePath } = require('./utils/path');
const assetPrefix = getBasePath();
// Plugins loader
const cssLoader = withCSS(withImageLoader({ env: exportEnvs }));
const imagesLoader = withImages({
assetPrefix,
});
const pwaLoader = withPWA({
target: 'serverless',
poweredByHeader: false,
assetPrefix,
pwa: {
dest: 'public',
subdomainPrefix: assetPrefix,
sourcemap: false,
},
});
// Next configuration
const nextConfig = {
assetPrefix,
publicRuntimeConfig: {
basePath: assetPrefix,
},
};
module.exports = withPlugins([
[cssLoader],
[pwaLoader],
[imagesLoader],
nextConfig,
]);
I saw that the recent version of next-images was updated in order to fix this, but for some reason I can't get mine to work. Is there something wrong with my configuration?
module.exports = withPlugins([withBundleAnalyzer, [withImages, {}]], {
...antConfig,
env: {
PRODUCTION_API_URL: process.env.PRODUCTION_API_URL,
},
});
Hello!
I think the regex on this line isn't working as intended:
Line 24 in 3095b20
In particular, the \.
doesn't require that the file extension start with a period.
Here's an example.
const extensions = ["png", "jpg", "jpeg", "gif", "ico", "image\\.svg"];
const regex = new RegExp(`\.(${extensions.join('|')})$`)
console.log(regex.test("foo.png")); // true, correct behavior
console.log(regex.test("foo.svg")); // false, correct behavior
console.log(regex.test("foo_image.svg")); // true, **incorrect behavior**
console.log(regex.test("foo.image.svg")); // true, correct behavior
Notice how foo_image.svg
is considered a match even though there's an underscore, not a period, before the word image
.
The issue goes away if another forward slash is added to the RegExp line as such:
new RegExp(`\\.(${extensions.join('|')})$`)
I'd be happy to send a PR if you'd like! 🙇🏻
Leaving a note here as this was very difficult to debug. If you're using nx
and next-images
together then an upgrade to nx 12 will break next-images because they (idiotically) decided to add in svgr
by default. So if you were using next-images
for SVGs nx is now going to try and process SVGs into react components, which will break your existing project.
I was combining next-images
with react-inlinesvg
and got this exact error. The solution isn't yet documented on nx.dev, but I figured it out by reading a bugfix PR's source code. You need to make use of withNx
in next.config.js
like so:
const withImages = require("next-images");
const withNx = require("@nrwl/next/plugins/with-nx");
module.exports = withImages(
withNx({
nx: {
svgr: false,
},
})
);
I also needed to forcibly update @nrwl/cli
to get builds to work. In the end, these are the relevant bits from package.json
:
{
"dependencies": {
"next": "^10.2.3",
"next-images": "^1.7.0",
"nx": "12.3.6",
"react-inlinesvg": "^2.3.0",
"webpack": "4.46.0"
},
"devDependencies": {
"@nrwl/cypress": "12.3.6",
"@nrwl/eslint-plugin-nx": "12.3.6",
"@nrwl/jest": "12.3.6",
"@nrwl/nest": "12.3.6",
"@nrwl/next": "12.3.6",
"@nrwl/node": "12.3.6",
"@nrwl/react": "12.3.6",
"@nrwl/web": "12.3.6",
"@nrwl/workspace": "12.3.6",
"@nrwl/cli": "^12.3.6",
"@nrwl/nx-cloud": "12.2.1"
},
"engines": {
"node": ">=14.13.1 <15.0.0",
"npm": ">=6.14.8 <7.0.0"
}
}
When I installed next-images next/image started to give a "Module not found" error. I looked here and thought this might be my answer, but came up short.
Update: For some reason next/image isn't in my next install. Weird. Not a next-images issue. sorry.
This is my next.config.js
file. Any idea why this isn't working
const withSass = require('@zeit/next-sass');
const withImages = require('next-images');
module.exports = withSass({
sassLoaderOptions: {
includePaths: ['./styles/']
},
cssModules: true,
cssLoaderOptions: {
importLoaders: 1,
localIdentName: '[local]___[hash:base64:5]'
},
withImages: withImages
});
I tried this also
const withSass = require('@zeit/next-sass');
const withImages = require('next-images');
module.exports = withSass({
sassLoaderOptions: {
includePaths: ['./styles/']
},
cssModules: true,
cssLoaderOptions: {
importLoaders: 1,
localIdentName: '[local]___[hash:base64:5]'
},
withImages: withImages()
});
The error says I need an appropriate loader.
Next.js now imports images from css/sass/scss file by itself and we use next-images
package together with it, it breaks the native image import in css/sass/scss functionality.
As suggested in this issue, the solution is to check the issuer
in the webpack
rule specification.
I can create a PR with the fix if you're interested.
I need to change CDN host after build when server starts.
I try it with statically generated pages (using revalidate
option of getStaticProps
) and with dynamically generated pages.
All urls change correct except urls to images which I import from js.
I have tried to use dynamicAssetPrefix
. My next.config.js
looks like this:
const withImages = require('next-images');
module.exports = withImages({
assetPrefix: process.env.CDN,
dynamicAssetPrefix: true,
webpack(config, options) {
return config;
},
});
If I set CDN
at build time then this CDN host still does not change when I change CDN
env and start server.
And if I leave CDN
env empty at build time then I get an error TypeError: Cannot read property 'nextImagesAssetPrefix' of undefined
during build.
Is it a bug? or I do something wrong?
What is a correct way to use dynamicAssetPrefix
?
https://i.imgur.com/Z1Ga74q.png
Here is the error I'm getting
When importing a shared React component from another workspace that imports an image using require("../path/to/image
) or import image from '../path/to/image'
, it throws the same error
����
^
SyntaxError: Invalid or unexpected token
Our use case: We want to use next-images for everything except SVGs. For SVG's we want to use a babel plugin to handle svg imports and include them directly into the rendered output.
Setting exclude
to /\.svg$/,
works fine however we lose the ability to import SVG's in css/scss files entirely.
At the moment we are adding the following to our webpack config:
config.module.rules.push({
test: /\.svg$/,
issuer: /\.scss/,
use: [{
loader: require.resolve('url-loader'),
options: {
fallback: require.resolve('file-loader'),
publicPath: `/_next/static/images/`,
outputPath: `${options.isServer ? "../" : ""}static/images/`,
name: "[name]-[hash].[ext]"
}
}]
});
Which works great, but it would be nice if this was configurable, such as:
imageProcessingRules: [
{
extension: 'svg',
issuer: /\.scss/
}
]
Where all extension
s would be combined into the exclude option for the main rule.
If this is something you'd be happy to include, I can do up a PR.
Hello thank you for your maintaining.
I wanna reduce filename in production.
So how about add uglifyFileName
option?
If you allow, I wanna send a PR using this library.
Using next 10.0.3, it seems that async redirects()
in the config is ignored if using next-images.
Other config options work fine, but pages which should be redirecting just return 404. Removing next-images fixes the issue.
Feature request: make options.limit
configurable
The plugin perfectly works for requiring/importing images in ReactComponents
I just need it to work also for images in the styling files as following
.class {
background-image: url('/images/hero/home.jpg');
}
Can this plugin be extended to handle this scenario as well?
I am trying to use this plugin with nextjs 9.
When importing an image inside a .js file, it works fine, but fails when importing inside a tsx file.
I've just encountered an issue were assetPrefix
was undefined and was setting my image assets to be undefined/_next/static...
I believe it is on this line when creating the new nextConfig
Line 5 in 73b4992
if nextConfig
already has assetPrefix set as undefined
it does not default to ""
and then causes this to created as a string...
In my config i have the following:
assetPrefix: process.env.PUBLIC_URL,
...which is only set when I am deploying to prod, for local dev this env variable is... undefined
I'll expand on this later, i just wanted to log this issue now as I've resolved it for myself by defaulting in my config..
assetPrefix: process.env.PUBLIC_URL || '',
I'm keeping images in an images/
folder and URLs in a data file. I'd like to dynamically import the images so I can load a large number of images easily.
I thought this could be done using dynamic imports, however it seems that functionality only supports Js modules. Will this be supported in the future or am I totally off the mark on this one?
import dynamic from 'next/dynamic';
import urls from '../urls';
const images = urls.map(url => dynamic(() => import(url));
I'm getting the error Error: Cannot find module.
This is just a heads-up for you.
require.context()
doesn't use next-images
webpack rules as discussed here. Works as expected when you comment out issuer property. That's a webpack bug.
Hello,
issuer: /\.\w+(?<!(s?c|sa)ss)$/i,
Create JS crash on Safari / IOS
To tempory fix, i use @1.3.0
If you have a other solution
As google pagespeed is asking us to deliver images in more performant formats I was wondering if you might be able to add support for .jp2/.jpx image formats.
At this moment Safari and iOS Safari do not support .webp.
Thanks!
I use bottom config, but no work
const withSass = require('@zeit/next-sass');
const withImages = require('next-images');
module.exports = withImages(
withSass({
sassLoaderOptions: {
includePaths: ['./styles/']
},
cssModules: true,
cssLoaderOptions: {
importLoaders: 1,
localIdentName: '[local]___[hash:base64:5]'
}
})
);
scss文件中
background: url(/static/images/[email protected]) top center;
Originally posted by @arefaslani in #10 (comment)
Hi, I'm trying to add the webpack 5 beta but I have this error on compilation:
Invalid configuration object. Webpack has been initialized using a configuration object that does not match the API schema
- configuration[0].module.rules[2].issuer has an unknown property 'test'.
name: 'ValidationError',
errors: [
{
keyword: 'oneOf',
dataPath: '[0].module.rules',
schemaPath: '#/properties/rules/oneOf',
params: [Object],
message: 'should match exactly one schema in oneOf',
schema: [Array],
parentSchema: [Object],
data: [Array],
children: [Array]
},
{
keyword: 'oneOf',
dataPath: '[1].module.rules',
schemaPath: '#/properties/rules/oneOf',
params: [Object],
message: 'should match exactly one schema in oneOf',
schema: [Array],
parentSchema: [Object],
data: [Array],
children: [Array]
}
],
Maybe are you missing the oneOf
rule before the use
one?
I would like to specify that the components and scss files are loaded from node_modules
Example:
//index.scss
...
.global-footer {
background: #34322f url('./images/footer-bg.png');
}
The image is loading as I commented "issuer: /.\w+(?<!(s?c|sa)ss)$/i,", but it is currently in base64 encoded version.
I would like to have the following result:
url('/_next/static/images//footer-bg-5216de428a8e8bd01a4aa3673d2d1391.png');
Finally I solved the problem as follows:
config.module.rules.push(
{
test: /\.(png|jpe?g|gif|ico)$/i,
issuer: /\.scss$/i,
exclude: [/\.(js|jsx|ts|tsx)$/],
use: [
{
loader: require.resolve("url-loader"),
options: {
limit: false,
fallback: require.resolve("file-loader"),
publicPath: `${assetPrefix}/_next/static/images/`,
outputPath: `${isServer ? "../" : ""}static/images/`,
name: "[name]-[hash].[ext]",
esModule: false
}
}
]
}
);
Which folder did you mean to put the images?
I created an images
folder inside the public
folder but still got the error.
As your guide, the image should be located in the same directory of the code file, that's so weird.
Currently this plugin only works if assetPrefix
is set at build step. (meaning it only support a static CDN)
This is quite hard to get working when considering apps running on multiple environments; where each environment could have a different CDN (like a production CDN vs a staging CDN.)
Furthermore, Next.js expose many ways to make the assetPrefix dynamic (like switching CDN domain based on the app domain, etc.) By requiring a static CDN, this plugin cannot support any of those use cases.
The package.json indicates MIT License which is good but it's also a good practice to include a LICENSE or license file in your repo and this file would also have a line to specify who is the copyright holder.
Some company's need to see those copyrights to allow their employees to use open source packages...
In component file: <img src={require('../static/images/icon.png')} />
In next.config.js
:
const withImages = require('next-images')();
...
module.exports = withPlugins([withImages, sourceMaps, withBundleAnalyzer],
{
....
});
Error:
wait - compiling...
error - ./static/images/icon.png 1:0
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)
Version: 1.6.2
i see the demo like module.exports = withImages({ ...... .....
but i also want to use with next-transpile-module
, so how i can achieve it ?
Not to sure what happened but reverting to 1.8.2 without ^ solves the issue :)
`./src/images/buttons/searchButton.svg
Module parse failed: Unexpected token (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
|
| <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
`
I would like to know if this lib is breaking the core functionalities like CDN caching when deployed to zeit.now?
Does next-images supports absolute path?
I'm trying to import a .svg but I'm getting an error.
Error:
Error: /Users/v/project/src/components/home/Header.tsx: Cannot find module 'src/assets/menuIcon.svg' from '/Users/v/project/src/components/home'
next.config.js:
const withImages = require('next-images')
module.exports = withImages({
esModule: true
})
After upgrading to NextJS 11 the following errors are printed and the site never loads.
3|server | error - ./src/server/components/Footer/facebook.svg
3|server | TypeError: unsupported file type: undefined (file: undefined)
Our Next app still uses next-css
(despite built-in CSS support as of 9.2) because of some legacy requirements and subtle differences in how the two behave (next-css
allows imports of CSS outside of _app.js
).
Upgrading to 1.4.0 of next-images
broke our app:
$ next build && next export
Failed to compile.
./node_modules/slick-carousel/slick/slick-theme.css
ModuleParseError: Module parse failed: Unexpected character '' (1:7)
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)
> Build error occurred
Error: > Build failed because of webpack errors
at build (*/node_modules/next/dist/build/index.js:12:900)
slick-theme.css
has image imports.
This change 211f664#diff-168726dbe96b3ce427e7fedce31bb0bc appears to assume Next's built-in CSS support is always present, but that isn't necessarily the case (depending on Next config). Backwards compatibility with custom configs is explicitly mentioned in the 9.2 post:
This new feature is fully backwards compatible. If you are using @zeit/next-css or other CSS related plugins the feature is disabled to avoid conflicts.
This is what my current next.config.js
looks like.
const withImages = require('next-images')
module.exports = withImages({
assetPrefix: 'https://cdn.jsdelivr.net/npm/simple-icons@v3/icons',
webpack(config, options) {
return config
}
});
As mentioned, I'm using the assetPrefix
option.
But how do I import it in different pages and components?
I've tried with src={require(
/css3.svg)}
but it doesn't work.
For example: https://www.npmjs.com/package/nextjs-basic-auth-middleware
Requires next.config.js:
module.exports = {
experimental: {
documentMiddleware: true
}
}
// or
module.exports = (phase, { defaultConfig }) => {
return {
experimental: {
documentMiddleware: true
}
}
}
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.