Reference External Javascript Library in .html files with angular-cli

偶尔善良 提交于 2020-01-06 04:47:07

问题


Receiving error 404 referencing a legacy javascript library in angular application. My question is why?

These are the characteristics of my build environment

  • Angular CLI: 1.6.0
  • Node: 7.10.0
  • OS: win32 x64
  • Angular: 4.4.6

The image below shows the tag in the index.html referencing the chart.js javascript file that was installed using node. I have checked the path and determined that the file is present at that location and would like to understand why I can't reference the javascript file directly in my html with the location in node_modules.

The image below shows the error that I receive trying to reference the javascript file in my html using the script tag

If a workaround is the answer, can the answer also contain the reason why the workaround is necessary using angular?


回答1:


This is possible using Angular Cli

Taking example of jssha js library

Step One

npm install jssha --save [using jssha for this demo]
If it is your own custom file place it in the scripts array of angular-cli.json skip this step 1

Step two

Add the jssha scripts file in .angular-cli.json file
"scripts": [ "../node_modules/jssha/src/sha.js" ]

Step three Adding a var in component to be used as a global variable

//using external js modules in Angular Component
declare var jsSHA: any; // place this above the component decorator
shaObj:any;
hash:string;
this.shaObj = new jsSHA("SHA-512", "TEXT");
this.shaObj.update("This is a Test");
this.hash = this.shaObj.getHash("HEX")

Take a look @ this link. details for the same with typings and without it. I have used bootstrap and jquery with Angular in that project, you can check the repo too.

Working example




回答2:


Usually in webservers you have to define specific folders that are presented to the public. It is always depending on your webserver but you can usually add new folders that can be accessed by something like a browser. Otherwise all your content may just be public, which is usually not what you want.

In your case it just seems like your webserver does not use the node_modules folder for public access, so if you want to use that script inside of it you probably have to declare it as a public folder. This is of course dependent on your server, here's an example for nodejs with express framework.

app.use(express.static('node_modules'));



来源:https://stackoverflow.com/questions/47687027/reference-external-javascript-library-in-html-files-with-angular-cli

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!