Home > Mobile >  Failed to load module script when importing a .jpg file in a javascript file
Failed to load module script when importing a .jpg file in a javascript file

Time:04-09

I'm just trying to import an image in a javascript file to test webpack assets. When I start the Live Server extenssion in VS-Code, I should see the image but I receive following Error:

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

index.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Hello world!</title>
  </head>
  <body>
    <script type="module" src="./src/index.js"></script>
  </body>
</html>

index.js

import tech2 from "./tech2.jpg";

function addImage() {
  const img = document.createElement("img");
  img.alt = "Tech.";
  img.width = 300;
  img.src = tech2;
  const body = document.querySelector("body");
  body.appendChild(img);
}

addImage();

webpack.config.js:

module.exports = {
  entry: "./src/index.js",
  output: {
    path: __dirname   "/dist",
    filename: "bundle.js",
  },
  mode: "none",
  module: {
    rules: [
      {
        test: /\.(jpg|png)$/,
        type: "asset/resource",
      },
    ],
  },
};

There is nothing in the body!:

There is nothing in the body.

CodePudding user response:

Webpack has features that can take an import pointing to an image file and convert it to a URL. Browsers can't do that, the only thing you can use import to load in a browser is a JavaScript module.

You have a Webpack config, but you aren't using it.

  • You said you were using VS Code Live Server
  • The url in the browser points to src not dist (so you aren't running the webpack build pipeline manually and using the results).

If you want to use Webpack while you develop, use the Webpack dev server instead of the VS Code Live Server extension.

  • Related