我正在使用ArcGIS JSAPI 4.12,希望使用空间幻象在地图上绘制军事符号。

当我将milsymbol.js添加到脚本中时,控制台返回错误

无法在模块外部使用import语句

所以我添加type="module"到脚本中,然后它返回

Uncaught ReferenceError: ms未定义

这是我的代码:

<link rel="stylesheet" href="https://js.arcgis.com/4.12/esri/css/main.css">
<script src="https://js.arcgis.com/4.12/"></script>
<script type="module" src="milsymbol-2.0.0/src/milsymbol.js"></script>

<script>
    require([
        "esri/Map",
        "esri/views/MapView",
        "esri/layers/MapImageLayer",
        "esri/layers/FeatureLayer"
    ], function (Map, MapView, MapImageLayer, FeatureLayer) {

        var symbol = new ms.Symbol("SFG-UCI----D", { size: 30 }).asCanvas(3);
        var map = new Map({
            basemap: "topo-vector"
        });

        var view = new MapView({
            container: "viewDiv",
            map: map,
            center: [121, 23],
            zoom: 7
        });
    });
</script>

所以,无论我是否添加type="module",总会有错误。但是在Spatial Illusions的官方文档中,脚本中没有type="module"。我现在真的很困惑。他们如何在不添加类型的情况下让它工作呢?

文件milsymbol.js

import { ms } from "./ms.js";

import Symbol from "./ms/symbol.js";
ms.Symbol = Symbol;

export { ms };

当前回答

触发此错误是因为您在HTML文件中链接到的文件是该文件的未绑定版本。 要获得完整的捆绑版本,你必须安装npm:

npm install --save milsymbol

这将把完整的包下载到node_modules文件夹中。

然后,您可以在node_modules/milsymbol/dist/milsymbol.js中访问独立的微型JavaScript文件

您可以在任何目录中执行此操作,然后将下面的文件复制到/src目录。

其他回答

我正在编写香草JavaScript。如果你做同样的事情,只需添加一个type="module"到你的脚本标签。

也就是之前的代码:

<script src="./index.js"></script>

更新后的代码:

<script type="module" src="./index.js"></script>`

我在尝试使用import Express.js时遇到了这个错误。

而不是从'express'进口express;

我使用const express = require('express');

只需在src中的<script>标记的名称和扩展名之间添加.pack。

例如:

<script src="name.pack.js">
    // Code here
</script>

错误的原因如下:

You're currently loading the source file in the src directory instead of the built file in the dist directory (you can see what the intended distributed file is here). This means that you're using the native source code in an unaltered/unbundled state, leading to the following error: Uncaught SyntaxError: Cannot use import statement outside a module. This should be fixed by using the bundled version since the package is using rollup to create a bundle. The reason you're getting the Uncaught ReferenceError: ms is not defined error is because modules are scoped, and since you're loading the library using native modules, ms is not in the global scope and is therefore not accessible in the following script tag.

看起来你应该能够加载这个文件的dist版本,在窗口上定义ms。请查看库作者提供的这个示例,以了解如何做到这一点。

在我的情况下,我更新了

"lib": [
      "es2020",
      "dom"
    ]

with

"lib": [
  "es2016",
  "dom"
]

在我的tsconfig中。json文件。