简体   繁体   中英

next-images Error: Module parse failed: Unexpected character '�'

I'm trying to load an image with next-images: when i type in the image name it works fine:

//Working
<Image src={require(`../../images/exampleImage.jpg` )}/>

but i dont want that i want dynamic url like this:

//Not working
<img src={require(`../../images/${image}.jpg` )}/>

i get this error:


Error: 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)

my next.config.js file:

const withImages = require("next-images");
module.exports = withImages();

i also tried this config:

module.exports = {
  webpack: (config, options) => {
    config.module.rules.push(
      {
        test: /\.(jpe?g|png|gif|woff|woff2|eot|ttf|svg)(\?[a-z0-9=.]+)?$/,
        loader: 'url-loader?limit=100000' 
      }
    )
    return config
  },
}

I tried many methods but none seems to work please help, thanks

If you're open to using the file-loader library to handle images on the project. You could install the library and set the rules like this on webpack:

...
config.module.rules.push(
  {
    test: /\.(png|jpeg|jpg|gif|svg)$/,
    use: {
      loader: "file-loader"
    },
  }
),

You can read more about file-loader from its documentation on webpack

Webpack is most likely trying to find & include your images at the build time. This cannot work with reading the name from a variable. You have 2 options:

  • manage images differently
  • if you have a finite (or rather short) list of images, just import all & use some kind of switch to control which image is displayed.

I had this issue too.

  • delete all your code in the next.config.js
  • add the below codes instead:
/** @type {import('next').NextConfig} */
const nextConfig = { 
    reactStrictMode: true,
    images: {
        dangerouslyAllowSVG: true,
        contentSecurityPolicy: "default-src 'self'; script-src 'none'; sandbox;",
    },
};
    
module.exports = nextConfig;

It resolved my problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM