Vanilla JS本地测试报错:Cannot use import statement outside a module
解决「Cannot use import statement outside a module」错误(Vanilla JS)
问题原因
你遇到的错误是因为index.js中使用了ES模块的import语法,但浏览器默认将未声明type="module"的<script>标签当作传统脚本执行,不支持模块语法。另外还有两个小问题:导入路径不符合ES模块规范,以及重复加载了data.js。
解决步骤
给
index.js的脚本标签添加type="module"
修改index.html中引入index.js的标签,明确告诉浏览器这是一个ES模块:<!-- 原代码 --> <script src="index.js"></script> <!-- 修改后 --> <script type="module" src="index.js"></script>修正导入路径
ES模块要求导入路径必须是相对路径(带./或../前缀)或绝对路径,修改index.js中的导入语句:// 原代码 import {data} from 'data.js'; // 修改后 import {data} from './data.js';移除不必要的
data.js脚本标签
因为index.js已经通过import加载了data.js,无需在index.html中单独引入,删除这一行:<script type="module" src="data.js"></script>
修改后的完整代码
index.html
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Supercluster Leaflet demo</title> <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.3/dist/leaflet.css" integrity="sha256-kLaT2GOSpHechhsozzB+flnD+zUyjE2LlfWPgU04xyI=" crossorigin="" /> <script src="https://unpkg.com/leaflet@1.9.3/dist/leaflet.js" integrity="sha256-WBkoXOwTeyKclOHuWtc+i2uENFpDZ9YPdf5Hf+D7ewM=" crossorigin=""></script> <link rel="stylesheet" href="cluster.css" /> <style> html, body, #map { height: 100%; margin: 0; } </style> </head> <body> <div id="map"></div> <script type="module" src="index.js"></script> </body> </html>
index.js
import {data} from './data.js'; /*global L */ // The rest not needed
data.js(保持不变)
const data = { "type": "Feature", "properties": { "name": "Coors Field", "amenity": "Baseball Stadium", "popupContent": "This is where the Rockies play!" }, "geometry": { "type": "Point", "coordinates": [-104.99404, 39.75621] } } export {data};
内容的提问来源于stack exchange,提问作者user994165
相关产品推荐
相关产品推荐

