Code Monkey home page Code Monkey logo

next-images's People

Contributors

aminkhademian avatar arctouch-rodrigoteobaldo avatar arefaslani avatar asgeo1 avatar benawad avatar danoc avatar dependabot[bot] avatar dislick avatar elliottsj avatar fracture91 avatar jeremybarbet avatar kylemh avatar mcansh avatar megazazik avatar mikaelbr avatar milanlempera avatar mitchellhuang avatar myoxocephalus avatar nicholaschiang avatar peter-jozsa avatar realshaunoneill avatar sboudrias avatar simnalamburt avatar techninja avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

next-images's Issues

Error: Module [the imported image] not found

I'm on NextJs 9.3.4 so I'm not using /static nor /public/static

steps to reproduce...

  • i place image in /public sub-dir
  • i call it using your import and API from within my /pages jsx files, as per docs
  • i reboot the local server after adding image to /pages jsx files
  • it fails to compile, with this exact error:

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.

How to use with MDX Remote?

I'm just wondering if you could share how this might be used to allow importing images within next-mdx-remote?

next-image config with @zeit/next-css

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?

creating multiple images with different sizes

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!

Does not work with images created at runtime

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?

Images are not served: 404 errors

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:

image
image

Could tags be pushed to GitHub?

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!

Support for typescript paths

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';

Breaks with next-pwa

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.

My implementation

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,
]);

Module parse failed - using SCSS to set background image

Screen Shot 2020-06-02 at 8 08 50 AM

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,
  },
});

File format regex doesn't properly escape first period

Hello!

I think the regex on this line isn't working as intended:

test: new RegExp(`\.(${nextConfig.fileExtensions.join('|')})$`),

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! 🙇🏻

Error parsing input in convertFromString - next-images and nx svg processing issue

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.

Screen Shot 2021-06-11 at 3 28 40 PM

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"
  }
}

Does next-images overwrite next/image?

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.

Not working with multiple module.exports

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.

Breaks with native css/sass/scss in Next.js 9.3+

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.

dynamicAssetPrefix does not work as expected

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?

Not working for yarn workspace shared component import

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

Provide the ability to exclude image imports for only certain file types

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 extensions 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.

RFC: uglify option

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.

Redirects not working when using next-images

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.

Can I use/tweak this plugin to also load images from scss files?

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?

assetPrefix is undefined

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

nextConfig = Object.assign({ inlineImageLimit: 8192, assetPrefix: "" }, nextConfig);

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 || '',

Issues with image dynamic import

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.

Regex not compatible IOS / Safari

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

Add support for jpeg 2000 for Safari and iOS Safari?

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!

You are using withImages as an option for configuring withSass plugin. They are two separate plugins. You should call use them this way:

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)

Not working with webpack 5 beta

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?

Loading background image from SCSS doesn't work

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
                            }
                        }
                    ]
                }
            );

It does not work

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.

Support dynamic assetPrefix

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.

Please add a license file and specify the copyright holder

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...

Error: You may need an appropriate loader to handle this file type

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

Is this lib breaking caching?

I would like to know if this lib is breaking the core functionalities like CDN caching when deployed to zeit.now?

Support absolute path

Does next-images supports absolute path?
I'm trying to import a .svg but I'm getting an error.

Code:
image

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
})

Broken in NextJS 11.0

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)

1.4.0 broken when used with custom CSS webpack config (e.g. next-css plugin)

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.

How to import CDN delivered images?

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.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.