【发布时间】:2021-02-13 16:00:34
【问题描述】:
我正在尝试复制 this small tutorial 来学习 Openlayers,但即使我直接复制并粘贴代码,也会遇到问题。
我遇到的第一个问题是 index.html。浏览器返回“Uncaught SyntaxError: Cannot use import statement outside a module”。所以,我在 index.html 中添加了“type='module'”,解决了这个问题。
但是,然后我收到一条错误消息,指出“Uncaught TypeError: Failed to resolve module specifier 'ol/ol.css'. Relative references must start with either "/'...”。我在 ./ol 中解压了 OpenLayers 文件,所以我只是将该路径添加到导入中,所以它们看起来像 import './ol/ol.css' 和 import './ol/ol/Map'。
现在,我收到“GET http://{myserverip}/Map/ol/ol/Map net::ERR_ABORTED 404 (Not Found)”的错误提示
当从 html 文件运行 javascript 时,如何正确导入 javascript 模块?我是不是完全走错了路?
javascript 导入:
import './ol/ol.css';
import Map from './ol/ol/Map';
import OSM from './ol/ol/source/OSM';
import TileLayer from './ol/ol/layer/Tile';
import TileWMS from './ol/ol/source/TileWMS';
import View from './ol/ol/View';
index.html 文件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Tiled WMS</title>
<!-- Pointer events polyfill for old browsers, see https://caniuse.com/#feat=pointer -->
<script src="https://unpkg.com/elm-pep"></script>
<style>
.map {
width: 100%;
height:400px;
}
</style>
</head>
<body>
<div id="map" class="map"></div>
<script type="module" src="main.js"></script>
</body>
</html>
需要注意的是,ol目录只包含ol.css、ol.css.map、ol.js、ol.js.map。 JavaScript 可以像那样从 ol/layer/Tile 导入 TileLayer(ol 是 ol.js 文件吗?)。
【问题讨论】:
-
你在使用一些构建系统吗?从示例链接中,他们有一个 package.json 将捆绑 javascript。
-
我不是。我刚刚从他们的网站下载了文件。
-
可能与this有关。您可能需要一些捆绑程序来解决您的导入问题。 Try these steps.
-
就是这样!谢谢!我不习惯这种发展,所以我做错了。
标签: javascript html openlayers