在使用 TypeScript 的 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"
}
}
https://www.npmjs.com/package/@types/openlayers https://www.npmjs.com/package/@types/openlayers
http://openlayers.org/ 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';
例如,各种代码集使用 TypeScript OpenLayers 定义
让 vectorSource: ol.source.Vector = new ol.source.Vector({
格式:new ol.format.GeoJSON(),
加载器:fnVectorLoader,
策略:(范围,分辨率)=> {
返回[范围];
}
});
并且引用类型定义的智能感知可以正常工作,指示定义文件的位置。
但是,当应用程序运行时,由于 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
似乎没有在 /node_modules 文件夹中搜索 OpenLayers 模块,而是在应用程序组件文件夹 (\ClientApp\components) 中搜索。
奇怪的是 React 和 jQuery 都有相似的类型定义文件和相应的节点模块,并且加载时没有任何问题。
我看到的唯一区别是 OpenLayers 类型定义文件夹是 /OpenLayers,而模块文件夹是 /node_modules/ol。此外,OpenLayers 定义文件中没有默认导出。
任何关于此问题原因的想法表示赞赏!