语法错误:导入声明只能出现在模块的顶层

Dav*_*Sky 8 javascript syntax import export

我正在尝试从“index.js”中的“test.js”导入函数

测试.js:

var testFunction = function test(){ alert("hello World") }

export testFunction
Run Code Online (Sandbox Code Playgroud)

在“index.js”的最顶部我尝试了以下语句:

import testFunction from './test.js'
Run Code Online (Sandbox Code Playgroud)

现在,当我在浏览器中运行 index.html 文件时,我的 Firefox 控制台中出现以下错误:

SyntaxError:导入声明只能出现在模块的顶层(第 1 行)

小智 11

有两种方法: 方案一(默认导出)

测试.js

var testFunction = function test() {alert('hello world')}

export default testFunction;
Run Code Online (Sandbox Code Playgroud)

你也可以做 export default function() {alert('hello world')};

索引.js

import testFunction from './test.js'
Run Code Online (Sandbox Code Playgroud)

解决方案2(命名导出)

测试.js

var testFunction = function test() {alert('hello world')};

export { testFunction };
Run Code Online (Sandbox Code Playgroud)

索引.js

import { testFunction } from './test.js'
Run Code Online (Sandbox Code Playgroud)

在这两种情况下你的 html 文件都有 <script type="module" src="./index.js"></script>

上面的行纠正了语法错误:导入声明可能只出现在模块的顶层。这是因为当您导入时,该文件现在变成了一个模块。您的index.js 文件现在是顶级模块。

如果您执行此操作并收到跨源请求块错误。您应该通过服务器完成工作。

进一步阅读模块


Dav*_*Sky 4

解决方案:

测试.js

var testFunction = function test(){ alert("hello World") }

export {testFunction}


Run Code Online (Sandbox Code Playgroud) 索引.js:
import testFunction from './test.js'

//...

Run Code Online (Sandbox Code Playgroud) html:
<script type="module" src="./index.js">

Run Code Online (Sandbox Code Playgroud)