我有一个小的web应用程序,现在我决定把它整理一下,把函数分离到functions.js文件中。
我正在导出这些并将其导入main.js文件中,但我收到了错误";未捕获的语法错误:意外的令牌"{"。
我在index.html 中定义它
<head>
<script type = "module" src="functions.js"></script>
</head>
<body>
<div id="root"></div>
<script type = "module" src="scripts.js"></script>
</body>
functions.js
export function hello() {
return "Hello";
}
export function hello2() {
return "Hello";
}
Main.js
import { hello, hello2 } from 'functions.js';
然而,当我使用";静态服务器";我收到了上面提到的错误。我不知道为什么会发生这种情况,因为代码看起来还可以?
您正在使用nodejs。它需要CommonJS模块语法。这意味着
export function hello() {
return "Hello";
}
成为
module.exports = function hello() {
return "Hello";
}
与import
相同
请在这里找到更多信息,尤其是第三个答案:
https://stackoverflow.com/a/60615051/4912528
而不是像这样导出:
export function hello() {
return "Hello";
}
export function hello2() {
return "Hello";
}
更改为:
function hello() {
return "Hello";
}
function hello2() {
return "Hello";
}
export default {hello, hello2}
我已经找出了问题所在。我正在中包装我的代码
$(function(){
import {hello, hello2} from './functions.js'
}
以帮助处理文档加载竞争条件。相反,我需要将导入移到这个之上
import {hello, hello2} from './functions.js'
$(function(){
}