问题
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