找不到模块:错误:无法使用 TypeScript 定义文件解析“openlayers”

Chr*_*isP 5 openlayers node.js typescript reactjs openlayers-3

在使用 TypeScrpt 的 Visual Studio 2017 React 应用程序中,有一个使用 OpenLayers v4.6.5 的组件 (Map.tsx)。

package.json 文件加载了@types/openlayers 和“ol”模块。

{
  "name": "mhc-maps",
  "private": true,
  "version": "2.0.0",
  "devDependencies": {
    "@types/history": "^4.6.2",
    "@types/jquery": "^3.3.1",
    "@types/openlayers": "^4.6.9",
    "@types/react": "^16.3.5",
    "@types/react-dom": "^16.0.4",
    "@types/react-hot-loader": "^3.0.6",
    "@types/react-router": "^4.0.23",
    "@types/react-router-dom": "^4.2.6",
    "@types/webpack-env": "^1.13.5",
    "aspnet-webpack": "^2.0.3",
    "aspnet-webpack-react": "^3.0.0",
    "awesome-typescript-loader": "^4.0.1",
    "css-loader": "^0.28.11",
    "event-source-polyfill": "^0.0.12",
    "extract-text-webpack-plugin": "^3.0.2",
    "file-loader": "^1.1.11",
    "foundation-sites": "6.4.3",
    "isomorphic-fetch": "^2.2.1",
    "jquery": "^3.3.1",
    "json-loader": "0.5.4",
    "ol": "^4.6.5",
    "react-dom": "^16.3.1",
    "react-hot-loader": "^4.0.1",
    "react-router-dom": "^4.2.2",
    "style-loader": "^0.20.3",
    "typescript": "^2.8.1",
    "url-loader": "^1.0.1",
    "webpack": "^4.5.0",
    "webpack-hot-middleware": "^2.21.2"
  }
}
Run Code Online (Sandbox Code Playgroud)

https://www.npmjs.com/package/@types/openlayers

http://openlayers.org/

请注意,TypeScript 定义文件位于 /node_modules/@types/openlayers 中,而 OpenLayers 模块位于 /node_modules/ol 中。

在 Map.tsx 中有一个 OpenLayers 类型定义文件的导入。

import * as React from 'react';
import * as $ from 'jquery';
import * as ol from 'openlayers';
Run Code Online (Sandbox Code Playgroud)

各种代码集使用 TypeScript OpenLayers 定义,例如

let vectorSource: ol.source.Vector = new ol.source.Vector({ format: new ol.format.GeoJSON(), loader: fnVectorLoader, strategy: (extent, resolution) => { return [extent]; } }) ;

并且引用类型定义的智能感知工作正常,指示定义文件所在的位置。

但是,当应用程序运行时,初始化时会显示以下错误,因为 React 加载了所有组件。

./ClientApp/components/Map.tsx
Module not found: Error: Can't resolve 'openlayers' in 'C:\Users\cp\Documents\Visual Studio 2017\Projects\Maps\Maps.Website\ClientApp\components'
 @ ./ClientApp/components/Map.tsx 13:0-33
 @ ./ClientApp/components/Layout.tsx
 @ ./ClientApp/routes.tsx
 @ ./ClientApp/boot.tsx
 @ multi react-hot-loader/patch event-source-polyfill webpack-hot-middleware/client?path=__webpack_hmr&dynamicPublicPath=true ./ClientApp/boot.tsx
Run Code Online (Sandbox Code Playgroud)

似乎没有在 /node_modules 文件夹中搜索 OpenLayers 模块,而是在应用程序组件文件夹 (\ClientApp\components) 中搜索。

奇怪的是,React 和 jQuery 都有相似的类型定义文件和相应的节点模块,并且加载没有任何问题。

我看到的唯一区别是 OpenLayers 类型定义文件夹是 /OpenLayers,而模块文件夹是 /node_modules/ol。此外,OpenLayers 定义文件中没有默认导出。

对此问题的原因的任何想法表示赞赏!