next.js: Can't import static files like images

version: v2.1.1

additional webpack config to next.config.js:

config.module.rules.push(
        {test: /\.(png|jpeg)$/, loader: 'url-loader?limit=8192'}
    )

then in my component: import image from '../static/enen.png'

it comes the error:

This module was not found:

* /static/enen.png in ./pages?entry

To install it, you can run: npm install --save /static/enen.png
{ Error: Cannot find module '/static/enen.png'
...

I have tried to change the url as ‘/static/enen.png’ , and in the css-in-jsx:

p {
  background-image: url('../static/enen.png')
}
//or
p {
   background-image: $(require('../static/enen.png'))
}

all above comes the same error: can’t find the module, I can get it using <img src="../static/enen.png"/>

hope your help.

About this issue

  • Original URL
  • State: closed
  • Created 10 years ago
  • Reactions: 39
  • Comments: 51 (7 by maintainers)

Most upvoted comments

If you add the image to the /static/ and then add the <img src="/static/image.png"/>? There is no need to load the image via the import.

@paulobarcelos it’s not a strong opinion. With our SSR setup, it’s kind a hard to it. (Since we don’t run webpack in the server) It’s doable, but we’ve much important other stuff to do.

@laoqiren why it’s not working simply use the image path like this:

background-image: url("/static/my-image.png")

Thanks @lededje for all those references and details.

@mehdijjz there are a lot of things we like to do. But sometimes, we can’t do all of them. But someday, we’ll be able to do it.

In the meantime, you need live without those features.

You can actually use webpack loaders in v5, someone already made a plugin for handling images: https://github.com/arefaslani/next-images

I don’t understand why would you want to use something like next-images or next-optimized-images if all they do is configuring file-loader/url-loader for you. These projects should be nothing more than gists people can contribute to and modify to their needs. Shouldn’t it output these files to /public folder anyway according to https://nextjs.org/docs/basic-features/static-file-serving ? Because cmon… _next/static/ isn’t even documented anywhere… This is definitely one hell of a mess looking at previous comments in this issue. Looking at the issues in linked projects I came to the assumption you’re better off just configuring webpack yourself…

config.module.rules.push({
    test: /\.(png|jpe?g|gif|svg)$/i,
    loader: "file-loader",
    options: {
    outputPath: '../public/assets/', // if you don't use ../ it will put it inside ".next" folder by default
    publicPath: 'assets/',
    }
});

Tested this only in development so far but at least it outputs the files according to the official docs and it’s clear to understand. I will update it in case it doesn’t work in production.

Next.js can serve static files, like images, under a folder called public in the root directory. Files inside public can then be referenced by your code starting from the base URL (/).

By the way, static folder was deprecated: https://nextjs.org/blog/next-9-1#public-directory-support

yes, It doens’t work just using background-image: url(“/static/my-image.png”).

@laoqiren The files must be within a /static/ directory relative to the pages directory. There are several examples of this working in the documentation.

You can actually use webpack loaders in v5, someone already made a plugin for handling images: This is not working

@lededje I want to use a webpack/babel loader to require images in my components.

e.g: <img src={require('./myImage.png')} />

@arunoda See, we have a problem here which we’re trying to solve, we’re not looking for workarounds in which you’re suggesting to use static images. how can we achieve requiring images (png, jpg, etc…) ? I personally prefer to have a customizable web pack for better customizability.

many of you are just saying things they dont understand here just to act woke, address the question at hand and move and stop raising questions and complicating issues.

Images by default are not accessible via import. You would need to modify the babelrc to allow for this. What data are you expecting to get returned from importing an image like that? a base64 encoded version of it? A browser resolvable path to it?

As @bugproof points out, you don’t need packages like next-images or next-optimized-images.

Here are steps on how you can import images. I copied how create-react-app does this.

  1. npm i --save-dev url-loader
  2. touch next.config.js if you don’t already have a next.config.js file.
  3. Add this.
module.exports = {
  webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
    config.module.rules.push({
      test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
      loader: require.resolve("url-loader")
    });

    return config;
  }
};

If you’re coming here from google, this is what seams best as of now : next-optimized-images

@Italox hardcoding image urls doesn’t work in case images needs to be served from a different domain than the app itself (like CDN for example).

@ruhaise

Hey check this out, https://github.com/zeit/next.js/blob/master/errors/static-dir-deprecated.md

I just saw this in my console after digging for a good bit. Was able to get it working by adding a public folder instead of static and I am using next@v^9.1.1

Have to second the sentiments from this comment https://github.com/vercel/next.js/issues/1935#issuecomment-648660605

This Image component is a drag and an example of a framework being too heavy handed. Leave this abstraction up to the end user and get out of the way.

Related: https://github.com/vercel/next.js/issues/18393

https://nextjs.org/docs/api-reference/next/image

👀   Not asking for these inline styles at all

<Image src="/images/hero-banner-example.png" width="" height="" />
<img src="/_next/image?url=%2Fimages%2Fhero-banner-example.png&amp;w=3840&amp;q=75" decoding="async" srcset="/_next/image?url=%2Fimages%2Fhero-banner-example.png&amp;w=3840&amp;q=75 1x" style="visibility: inherit; position: absolute; inset: 0px; box-sizing: border-box; padding: 0px; border: none; margin: auto; display: block; width: 0px; height: 0px; min-width: 100%; max-width: 100%; min-height: 100%; max-height: 100%;">

image


How about a hook to build just the URL?

const imgSrc = useNextImage('path/to/image');

// thanks I'll take it from here

loaders not working with styled jsx

<style jsx global>{ `
    body {
      background-image url('./lol.png')
    }
<style>

url('./lol.png') must be replace to http://localhost:3000/_next/static/chunks/images/lol-3cb46b372ab77d032576b9f70c83d1ff.png but this does not happen

I’m using next-optimized-images to import images, however it does not work in typescript, I’m getting messages like: Cannot find module './banner.png'. It does work with jsx though.

In my app, I <img src={require('images/myfile.png');} /> with nextjs. The reasons I want to do this:

  • Use webpack to verify a file exists
  • Requiring static files is one of the main reason webpack was built in the first place
  • Do specific things with loaders at load time (for example, I have a custom JSON webpack loader to process some large JSON files that would otherwise be loaded as static files

In my next.config.js, here’s an example of how i’ve added a rule for letting me require images in my source code

const config = {

  // See https://nextjs.org/docs/#customizing-webpack-config
  webpack: (webpackConfig, { isServer }) => {
    const { module } = webpackConfig;
    return {
      ...webpackConfig,
      module: {
        ...module,
        rules: [
          ...module.rules,
          {
            test: /\.(png|gif|jpg|jpeg)$/,
            use: [
              {
                loader: 'file-loader',
                options: {
                  emitFile: isServer,
                  publicPath: `/_next/static/`,
                  outputPath: `${isServer ? '../' : ''}static/`,
                  name: '[path][name].[ext]'
                }
              }
            ]
          }
        ]
      }
    };
  }
};

};

module.exports = config;

It’s unclear to me when nextjs does things with webpack, so I added emitFile: isServer in the hope that files will only be processed by webpack when the server bundle is built, and not duplicate work when the client bundle is built.

It’s unclear to me if this pattern adds any overhead to the build, because I’m not sure what webpack is doing under the hood with images/static assets in dev mode.

It looks like you can add static files in general by following the pattern of the withSass next-images plugin: https://github.com/twopluszero/next-images/blob/master/index.js and adding similar code for other file types in your next.config.js, or adding your own extension for it.

(I don’t understand the hard coding of publicPath: '/_next/static/' into the above linked plugin, shouldn’t this be from some config setting?)

I’m still playing with it, but I wish there was better first class support for this, or more documentation around it. Using a static/ folder defeats one of the core principles/reasons for using Webpack, which is a compile-time-provable dependency graph of all critical assets in your codebase. Using static/ by default is going back in time when we relied on global variables (path strings) to line up.

@arunoda yes, It doens’t work just using background-image: url("/static/my-image.png").

You can actually use webpack loaders in v5, someone already made a plugin for handling images: https://github.com/arefaslani/next-images

This doesn’t really work. I tried it.

/* eslint-disable */
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()
});

webpack loader fixed the problem, still typescript complains about it Cannot find module '../images/me.png'.ts(2307)