我试图了解 JS 中的模块导入。我在网上读了很多教程和文档,我觉得我现在已经掌握了理论,但我仍然无法将事情付诸实践。
所以,这就是我所做的。
我在同一路径中得到了三个文件:
try1.html
try2.html
f.js
try1.html:
<!-- try1.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Try1</title>
</head>
<body>
helloooo
<script type="module">
import {printHello} from './f.js';
document.body.appendChild(printHello());
</script>
</body>
</html>
try2.html:
<!-- try2.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Try2</title>
</head>
<body>
helloooo
<script>
function printHello() {
let p = document.createElement('p');
p.style = 'background: red'
p.textContent = 'helloooooooooooooo';
return p;
}
document.body.appendChild(printHello());
</script>
</body>
</html>
f.js:
// f.js
function printHello() {
let p = document.createElement('p');
p.style = 'background: red'
p.textContent = 'helloooooooooooooo';
return p;
}
export {printHello};
您可以看到我想做的只是调用一个函数,该函数将创建 DOM 元素并将其附加到文档。
如果我在 html 文件内的脚本标记中执行此操作,它会起作用(如 try2.html 情况);相反,如果我在 f.js 文件中定义该函数,然后将其导入到 try1.html 文件中,它将无法工作(也就是说,“hellooooooooooo”红色文本不会显示)。
这都是普通的 javascript 和 html,因为我没有使用 Node.js 或任何东西,我只是在浏览器(firefox,供参考)中打开 html 文件来加载页面。
我做错了什么?我无法理解它。请帮忙!