Error importing module in Javascript

Asked

Viewed 73 times

3

I am having a problem importing a Javascript module. I am using a Python HTTPS server to create my websites.

Filing cabinet: modules/index.js:

export function soma (c,d){
    return c + d
}

Filing cabinet index.js:

import {soma} from "./modules/index"

let value = soma(3,5)

console.log(value)

When I go to the console, this error appears:

Failed to load module script: The server responded with a non-JavaScript MIME type of "". Strict MIME type checking is enforced for module scripts per HTML spec.

How can I fix it?

  • Your sum Function is wrong!

1 answer

4

Assuming that your index js. is being imported in a tag script, I believe the error is that the type specification is missing MIME of the file you are trying to import.

In this case, try importing by informing the file extension .js in his index js.:

//                                    ↓↓ informe a extensão
import { soma } from "./modules/index.js";

let value = soma(3, 5); // 5 

console.log(value);

Strict MIME type checking is enforced for module scripts per HTML spec.

In order not to receive this error, it is mandatory to inform the file extension .js for scripts of the type type="module".

With the excellent help @Augustovasques we provided a good link to query, some points have to be taken into account:

the preference is that modules receive the extension . mjs because in the project phase lints look at this extension and treat the file properly and standalone interpreters look preferably for this extension.

In this case, to tag script with type="module", we better rewrite the file extension for the type module. In this case, let’s change .js for .mjs in the code:

//                                    ↓↓↓ informe a extensão .mjs
import { soma } from "./modules/index.mjs";

let value = soma(3, 5); // 5 

console.log(value);
  • 1

    @Augustovasques Good information, it is worth editing the answer and add this extra.

  • 1

    If I could give another +1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.