我在使用
Parcel作为打包工具与
TypeScript和
Leaflet v1.4(通过
npm安装,以及其类型定义)结合时遇到了类似的问题,并通过Gil的答案以稍微不同的方式解决了它。
import 'leaflet/dist/leaflet.css';
import 'leaflet-draw/dist/leaflet.draw.css';
import L, {
LatLngExpression,
FeatureGroup,
TileLayerOptions,
LayerEvent,
LeafletMouseEvent,
Marker,
Layer,
icon,
LayerGroup,
GeoJSON
} from 'leaflet';
import 'leaflet-draw';
import iconRetinaUrl from './assets/marker-icon-2x.png';
import iconUrl from './assets/marker-icon.png';
import shadowUrl from './assets/marker-shadow.png';
Marker.prototype.options.icon = icon({
iconRetinaUrl,
iconUrl,
shadowUrl,
iconSize: [25, 41],
iconAnchor: [12, 41],
popupAnchor: [1, -34],
tooltipAnchor: [16, -28],
shadowSize: [41, 41],
});
在另一个文件中,我添加了必要的声明,以便TypeScript
允许我导入png
图片,例如:
declare module "*.png" {
const content: string;
export default content;
}
此外需要注意的是,如果您使用了需要访问这些图片的Leaflet插件,您可能需要显式地分配它,例如Leaflet绘图插件也需要它。示例:
map.addLayer(drawLayer);
const drawControl = new L.Control.Draw({
draw: {
circle: false,
circlemarker: false,
marker: {
icon: Marker.prototype.options.icon,
},
},
edit: {
featureGroup: drawLayer,
},
});
map.addControl(drawControl);
map.on(L.Draw.Event.CREATED, event => {
const layer = (event as LayerEvent).layer;
drawLayer.addLayer(layer);
});