如何在angular.json中将脚本包含到头部

15

我希望在<head>标签中使用angular.json配置文件将aframe作为单独的包进行导入。

angular.json中,我有从我的node_modules导入的脚本:

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

这个被打包后在HTML的底部导入。

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

这并不理想,因为库明确要求我在 <head> 中导入。

另外,我希望将其作为一个独立的 bundle 导入:

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

23

您可以将脚本引用添加到Angular的angular.json中,例如包括jQuery库。

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

如果将inject设置为false,则不会将脚本注入index.htm中,最后我们只需为bundleName设置一个名称,这样该脚本将不会与其他脚本文件捆绑在一起,而是成为独立的文件,现在可以将脚本标签添加到头部标签中。

更新index.html并在头部包含脚本标签。

<!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>

鉴于我的当前设定,我能够实现这一点,但目标是在“head”中导入脚本。 - Dan
为什么你要把脚本放在<head>标签里? - Muhammed Albarmavi
该库特别要求我在<head>中导入。 - Dan
1
我已经更新了答案,只需将inject设置为false,并且您需要更新index.html文件并将脚本标签放置在头部。 - Muhammed Albarmavi
@Dan 很高兴能帮助。 - Muhammed Albarmavi
显示剩余3条评论

-1

你说得没错,但是这样脚本将会在主脚本加载后再加载。而在我的回答中,这个脚本将会在主脚本之前插入并在其之前加载。 - Muhammed Albarmavi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接