Home > other >  index.js and index.html in the same directory
index.js and index.html in the same directory

Time:11-27

I'm trying to learn React and Javascript. I try to understand how import and export works in ES6, so I put all three files index.html, index.js, and lib.js in the same folder. When I included index.js in my html file, it gave me the error

Uncaught TypeError: Failed to resolve module specifier "lib". Relative references must start with either "/", "./", or "../".

When I changed the name of index.js to index2.js, everything worked fine. I think the problem is that I was not supposed to put index.html and index.js in the same folder but I don't understand why. Can some please explain?

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>Document</title>
</head>
<body>
    <h1>Hello World!</h1>
    <script type="module" src="./index.js"></script>
</body>
</html>

index.js

import {square} from './lib.js'

console.log(square(3))

lib.js

export function square(x){
    return x*x
};

CodePudding user response:

It errors when you link index.js because 2 files can not have the same not name as any other file in the folder even if they have different file extensions. This is why when you change the name to index2.js it does not error.

CodePudding user response:

It's not really the files having same name in the same folder as the webpage, I found that if you use Firefox instead of Chrome, the problem goes away. Hope this will help.

  • Related