SyntaxError:import声明只能出现在模块的顶层

DCJ*_*nes 26 javascript

我试图在GitHub,GitHub SimpleBar上使用一个名为"Simplebar"的插件,但在下载脚本并查看simple.js脚本后,看起来它有一个错误"SyntaxError:import declarations可能只出现在顶层一个模块"

在simplebar.js文件的顶部有一些代码导入行:

import scrollbarWidth from 'scrollbarwidth'
import debounce from 'lodash.debounce'

import './simplebar.css'
Run Code Online (Sandbox Code Playgroud)

如果我查看我的浏览器调试器,我会看到一个错误:"SyntaxError:import declarations只能出现在模块的顶层".

有没有人试过我们这个插件.

非常感谢你的时间.

Eri*_*ran 34

我在Firefox(FF58)上得到了这个.我修复了这个:

  1. 它仍然是实验性的Firefox(从V54):你必须设置为true的变量dom.moduleScripts.enabledabout:config

来源:mozilla上的导入页面(请参阅浏览器兼容性)

  1. 添加type="module"到导入js文件的脚本标记中

<script type="module" src="appthatimports.js"></script>

  1. 导入文件已被前缀(./,/,../http://之前)

import * from "./mylib.js"

有关更多示例,此博客文章很好.

  • `type="module"` 为我解决了这个问题。 (37认同)
  • 两者都尝试过。都不起作用 (13认同)