当我看到这个声明时,我正在浏览标签的WHATWG规范async和defer属性<script>:
我经历了经典和模块脚本的WHATWG定义,但并没有真正清晰.有人可以向我解释我是5,Javascript中经典和模块脚本之间的区别吗?
我正在尝试从另一个JavaScript文件导入函数,但是中的import语句发生错误main.js。
main.js:
import {Event} from 'event.js';
let asdf = new Event("hi", "hi", "hi");
console.log(asdf.title);
console.log(asdf.mainText);
console.log(asdf.buttonSet);
Run Code Online (Sandbox Code Playgroud)
event.js:
export function Event(title, mainText, buttonSet) {
this.title = title;
this.mainText = mainText;
this.buttonSet = buttonSet;
}
Run Code Online (Sandbox Code Playgroud)
我查看了语法,没有发现任何错误:
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/import
另外,我在此链接中运行了代码片段,并得到了相同的错误。 浏览器中的ES6:未捕获的语法错误:意外的令牌导入
编辑: 更正的index.html文件:
<script src="scripts/main.js" type="module"></script>
Run Code Online (Sandbox Code Playgroud) 我在一个文件夹中有“三个”文件 1. index .html 2. index .js 3. helper .js
我想从中导出代码helper.js并将代码导入到index.js(我已经链接index.js到index.html)。
我确实喜欢那个 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<button id="btn">click</button>
<script src="./index.js"></script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
索引.js
import btn from './helper'
btn.addEventListener('click', function () {
window.alert('i am clicked')
})
Run Code Online (Sandbox Code Playgroud)
最后是helper.js
export let btn = document.getElementById('btn')
Run Code Online (Sandbox Code Playgroud)
然后我在 Chrome 浏览器中运行index.html文件。
Chrome 浏览器在控制台中显示此消息。
未捕获的语法错误:无法在模块外使用导入语句
请告诉我如何解决这个问题。我在 google 和 youtube 上搜索,我做了他们展示的同样的事情。结果,浏览器显示那个按摩。
<html>
<head>
<script src="./first.js"></script>
<script src="./second.js"></script>
</head>
</html>
Run Code Online (Sandbox Code Playgroud)
在first.js文件中,我想从second.js调用函数:
secondFun(); // calling a function from second.js file
Run Code Online (Sandbox Code Playgroud)
这是 second.js 文件:
function secondFun() {
console.log('second function called!!')
}
Run Code Online (Sandbox Code Playgroud) 我正在尝试在纯JavaScript中使用类,因此遇到错误“未捕获的SyntaxError:无法在模块外部使用import语句”并且无法解决它。
File1.js-主文件
import example from "./file2";
var test = new example();
Run Code Online (Sandbox Code Playgroud)
File2.js-类文件
export default class example {
constructor() {
console.log("hello world");
}
}
Run Code Online (Sandbox Code Playgroud)