【问题标题】:Esri maps with React and TypescriptEsri 使用 React 和 Typescript 映射
【发布时间】:2021-08-31 01:22:35
【问题描述】:

我创建了一个简单的反应应用程序:

npx create-react-app myapp --template typescript"

我想包含一个交互式地图组件。

按照https://developers.arcgis.com/javascript/latest/typescript-setup/ 的说明进行操作:

  1. 我添加了依赖项:
    npm install --save arcgis-js-api
    npm install --save @types/arcgis-js-api
  1. 我在public/index.html的head标签中添加了如下标签
    <link rel="stylesheet" href="https://js.arcgis.com/4.19/esri/themes/light/main.css">
    <script>
      var locationPath = location.pathname.replace(/\/[^/]+$/, "");
      window.dojoConfig = {
        packages: [
          {
            name: "app",
            location: locationPath + "/app"
          }
        ]
      };
    </script>
    <script src="https://js.arcgis.com/4.19"></script>
  1. 我像这样创建了我的组件 (Map2D):
import { useRef } from 'react';
import EsriMap from "esri/Map";
import MapView from "esri/views/MapView";

const Map2D = () => {

  const theView = useRef<HTMLDivElement>(null);

  if(theView && theView.current)
  {
    const map = new EsriMap({
      basemap: "streets-vector"
    });

    const view = new MapView({
      map: map,
      container: theView.current,
      center: [-118.244, 34.052],
      zoom: 12
    });
  }

  return (
    <div ref={theView} style={{ width: '100%', height: '100%', margin: '0', padding: '0' }}>      
    </div>
  );
}

export default Map2D;
  1. 我更新了 App.ts 以使用我的组件返回一个视图:
import './css/App.css';

import Map2D from './Components/Map2D';

function App() {
  return (
    <div className="App">
        <Map2D />
    </div>
  );
}

export default App;

之后,运行

yarn start

我明白了

Failed to compile.

./src/Components/Map2D.tsx
Module not found: Can't resolve 'esri/Map' in '/workspaces/myapp/src/Components'

应该如何更改这段代码,以便编译和运行?

【问题讨论】:

    标签: reactjs typescript esri


    【解决方案1】:

    您能否附上您的 webpack 配置的屏幕截图?我认为您在 webpack 配置的 resolve 部分中缺少此内容:

    alias: {
        "esri": path.resolve(__dirname, 'node_modules/arcgis-js-api/')
    }
    

    请在此处查看https://github.com/Esri/jsapi-resources/blob/master/4.x/webpack/demo/webpack.config.js

    【讨论】:

    • 使用npx create-react-app 生成的应用程序根本不包含 webpack.config.js。我将它与您在 module.exports 中显示的内容一起添加,解析,然后在 tsconfig.json 文件的“include”中添加“webpack.config.js”。不幸的是,我仍然遇到同样的错误。
    • 其他失败尝试:在tsconfig.json文件的“include”中添加“node_modules/arcgis-js-api/index.d.ts” 其他失败尝试:在开头添加/// &lt;reference types="arcgis-js-api" /&gt;组件的
    猜你喜欢
    • 2020-02-25
    • 1970-01-01
    • 2020-08-29
    • 2016-07-03
    • 1970-01-01
    • 2017-08-20
    • 2018-06-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多