How to include script to head in angular.json

佐手、 提交于 2021-02-20 09:06:50

问题


I would like to import aframe in the <head> tag using the angular.json config as a separate bundle.

Inside angular.json I have the script to import from my node_modules:

"scripts": [
    "node_modules/aframe/dist/aframe-v1.0.0.min.js"
]

This is bundled and imported at the bottom on the html body.

<body>
    <app-root></app-root>
    ...
    <script src="scripts.js" ...>
</body>

This is not desirable as the library specifically requests that I import in the <head>.

Additionally, I would like to import it as a separate bundle:

"scripts": [
  { "input": "node_modules/aframe/dist/aframe-v1.0.0.min.js", "bundleName": "aframe-v1.0.0.min" }
]

回答1:


you can add the script reference to angular.json like this as example include jquery library

"scripts": [
   {
    "input": "node_modules/jquery/dist/jquery.min.js",
    "inject": false,
    "bundleName": "jquery"
   }
]

then set inject to false will not injected the script to index.htm, finaly we just set a name for bundleName this way the script will not bundle with other script file and will be standalone file , and now you can add the script tag to the header tag

update the index.html and include the script tage at the header

<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <title>Portfolio</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <script src="jquery.js"></script> <!-- 👈 -->
</head>

<body>
  <app-root></app-root>
</body>

</html>



回答2:


You can use a service to inject it in the head.

This answer can help you : https://stackoverflow.com/a/44016611/8573150



来源:https://stackoverflow.com/questions/59416254/how-to-include-script-to-head-in-angular-json

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