【问题标题】:index.js and index.html in the same directoryindex.js 和 index.html 在同一目录下
【发布时间】:2022-01-04 21:45:22
【问题描述】:

我正在尝试学习 React 和 Javascript。我试图了解 importexport 在 ES6 中是如何工作的,所以我将所有三个文件 index.htmlindex.jslib.js 放在同一个文件夹中。当我在我的 html 文件中包含 index.js 时,它给了我错误

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

当我将 index.js 的名称更改为 index2.js 时,一切正常。我认为问题在于我不应该将index.htmlindex.js 放在同一个文件夹中,但我不明白为什么。可以解释一下吗?

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
};

【问题讨论】:

    标签: javascript html import module export


    【解决方案1】:

    链接 index.js 时会出错,因为 2 个文件不能与文件夹中的任何其他文件同名,即使它们具有不同的文件扩展名。这就是为什么当您将名称更改为 index2.js 时它不会出错。

    【讨论】:

      【解决方案2】:

      其实并不是网页同文件夹中的同名文件,我发现如果你用Firefox代替Chrome,问题就消失了。

      【讨论】:

        猜你喜欢
        • 2014-09-19
        • 2013-07-06
        • 2019-09-30
        • 1970-01-01
        • 2017-07-07
        • 1970-01-01
        • 1970-01-01
        • 2023-03-20
        • 2021-04-04
        相关资源
        最近更新 更多