0

I am trying to import image in JS file like this

import image from "./image/bg.png"

and in the script tag <script type="module" src="./index.js"></script>

but I got an error - Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "image/png". Strict MIME type checking is enforced for module scripts per HTML spec.

how do I do it

  • 1
    How do you want to use that "imported" image? – NickG May 25 '22 at 08:14
  • 1
    You cannot direcly import an image file like that. Depening on how you want to use your image, you can do different things. Load it via img tag in html (``), or load it in javascript (`const img = new Image("path_to_image");`). – NickG May 25 '22 at 08:15
  • @NickG i wanna use the image to build mario game platfoms and i dont how but the tutorial i am following import the image like this - import image from "./image/bg.png" –  May 25 '22 at 08:21
  • You need an extra package to use an image like that: https://stackoverflow.com/a/48399486/8788847 – NickG May 25 '22 at 08:37
  • I would guess the tutorial uses the image as javascript image object. So you should be fine if you do `const image = new Image("./image/bg.png");` and use that object instead of importing it. – NickG May 25 '22 at 08:40
  • @NickG [link](https://youtu.be/4q2vvZn5aoo ) here is the tutorial link if you plzz clarify me what happening (timing - 58:00 ) –  May 25 '22 at 09:02
  • @NickG i am asking you for learning purpose please –  May 25 '22 at 09:04
  • Actually you just get another error, but for the same reason as in the tutorial. Essentially what he does in the tutorial is using a server package (canvas-boilerplate) which has a dependency to the file-loader package. That server package allows for importing images. This sound to me like bad practise. Setting up a server for just the purpose of serving images as modules sounds like a lot of overhead. – NickG May 25 '22 at 09:33
  • 1
    You can look up that part in https://github.com/christopher4lis/canvas-boilerplate/blob/master/webpack.config.js. In line 24 the package defines which file extensions should be treated with the file-loader, and line 27 defines the loader package to should be used for these files. – NickG May 25 '22 at 09:35
  • @NickG thanks a lot i am completely satisfied with ur answer –  May 25 '22 at 11:28

0 Answers0