如何使用Angular 5 CLI加载第三方库shpjs?
在Angular 5中配置第三方库shpjs的踩坑与解决
问题场景
我最近在Angular 5项目里想用上shpjs这个第三方库,参考了第三方库加载的相关方案,在Angular CLI的配置文件里给scripts属性添加了这个库的路径:
"scripts": [ "../node_modules/shpjs/dist/shp.js" ],
项目构建完全正常,但奇怪的是这个脚本并没有出现在index.html里。按照文档的说法,配置了全局脚本后应该会自动像手动添加<script>标签那样加载,当时我还以为是漏了什么关键配置步骤。
解决过程
后来才发现,配置本身是没问题的! 问题出在组件里的导入语句上。只要在需要使用shpjs的component.ts文件里加上正确的导入:
import * as shp from 'shpjs';
之后测试功能就完全正常了,比如我写的这个测试函数:
openAsGeoJson(url: string) { url = 'http://calvinmetcalf.github.io/shapefile-js/files/TM_WORLD_BORDERS_SIMPL-0.3.zip'; shp(url).then(function (data) { if (data) { console.log('shapefile data received'); console.log(data.length); console.log(data); } }); }
运行后控制台能正常输出shapefile的数据,问题顺利解决。
我的环境信息
Angular CLI: 1.6.3 Node: 7.10.1 OS: win32 x64 Angular: 5.2.0 ... animations, common, compiler, compiler-cli, core, forms ... http, language-service, platform-browser ... platform-browser-dynamic, router @angular/cli: 1.6.3
内容的提问来源于stack exchange,提问作者JC5577
相关产品推荐
相关产品推荐

