Javascript 语法错误:导入声明只能出现在模块的顶层
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42237388/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
SyntaxError: import declarations may only appear at top level of a module
提问by DCJones
I am trying to use a plugin called "Simplebar" found on GitHub, GitHub SimpleBarbut after downloading the scripts and looking at the simple.js script, it looks like it has an error "SyntaxError: import declarations may only appear at top level of a module"
我正在尝试使用在 GitHub、GitHub SimpleBar上找到的名为“Simplebar”的插件,但在下载脚本并查看 simple.js 脚本后,它似乎有一个错误“SyntaxError:导入声明可能只出现在顶层一个模块”
At the top of the simplebar.js file there are some import lines of code:
在 simplebar.js 文件的顶部有一些导入代码行:
import scrollbarWidth from 'scrollbarwidth'
import debounce from 'lodash.debounce'
import './simplebar.css'
If I look in my browser debugger I see an error: "SyntaxError: import declarations may only appear at top level of a module".
如果我查看浏览器调试器,我会看到一个错误:“语法错误:导入声明可能只出现在模块的顶层”。
Has anyone tried to us this plugin.
有没有人试过给我们这个插件。
Many thanks in advance for your time.
非常感谢您抽出宝贵时间。
回答by Eric Masseran
I got this on Firefox (FF58). I fixed this with:
我在 Firefox (FF58) 上得到了这个。我用以下方法解决了这个问题:
- It is still experimental on Firefox (from v54):
You have to set to true the variable
dom.moduleScripts.enabledinabout:config
- 它仍然是实验性的Firefox(从V54):你必须设置为true的变量
dom.moduleScripts.enabled中about:config
Source: Import page on mozilla (See Browser compatibility)
- Add
type="module"to your script tag where you import the js file
- 添加
type="module"到您导入 js 文件的脚本标签
<script type="module" src="appthatimports.js"></script>
<script type="module" src="appthatimports.js"></script>
- Import files have to be prefixed (
./,/,../orhttp://before)
- 导入文件必须加前缀 (
./,/,../或http://之前)
import * from "./mylib.js"
import * from "./mylib.js"
For more examples, this blog postis good.
有关更多示例,这篇博文很好。

