Bower能否自动将<script>标签写入index.html?

62

我正在使用Yeoman的Backbone生成器,并运行了以下命令:

bower install backbone.localStorage -S

我需要手动将这个插入到index.html中:

<script src="bower_components/backbone.localStorage/backbone.localStorage.js"></script>
有没有一种方式让Bower自动插入<script>标签?我认为使用Bower的好处之一就是不必弄清楚包含脚本的顺序,对吗?
4个回答

42

只需运行

grunt bowerInstall 

运行bower install命令后


1
嗯,奇怪,我刚刚运行了bower install socket.iogrunt bower-install,我的grunt serve输出显示了>> File "app/index.html" changed. ... Reload app/index.html ... Completed in 0.000s at Wed Mar 19 2014 14:08:13 GMT+0100 (CET) - Waiting...,但是我没有在我的app/index.html文件中看到任何变化。为什么? - Ashesh
3
对我来说,“grunt bower-install”出现了错误。 我不得不使用“grunt bowerInstall”。 - Scott Marchant
是的,名称已于2014年2月10日更改(https://github.com/stephenplusplus/grunt-bower-install/commit/e0481a097e5f3ed47c9612b80be3d0af1cecdfc1),我已更新我的答案。 - mvilrokx
有趣的是,对我有效的命令是 grunt bower-install,grunt 版本为 v0.4.5 - fguillen
1
可以通过实时重新加载自动完成;-) watch: { bower: { files: ['bower.json'], tasks: ['wiredep'] } - Patrick Ferreira
参考链接如下:https://www.npmjs.org/package/grunt-bower-install - Wint

16

你可以使用wiredep将依赖从bower推入你的HTML代码中。这是当你运行yo angulargenerator-angular使用的方法

var wiredep = require('wiredep');
wiredep({
   directory: 'app/bower_components',
   bowerJson: JSON.parse(fs.readFileSync('./bower.json')),
   ignorePath: 'app/',
   htmlFile: 'app/index.html',
   cssPattern: '<link rel="stylesheet" href="{{filePath}}">'
});

不错的发现!这是 wiredep 文档的链接 https://github.com/stephenplusplus/wiredep - Mark Karwowski
我在安装Bootflat之后进行了这个操作,但是没有将任何脚本或CSS添加到我的index.html文件中。 - Paranoid Android

8
Bower不会为这样的特定功能添加支持,但很快将允许您在“bower install”新软件包后指定要执行的操作。 这将被称为“postinstall”,类似于npm。
与此同时,我创建了一个库来帮助解决这个问题。由于您正在使用yeoman,请将“grunt-bower-install”作为npm的“devDependency”添加,然后按照此处的说明操作:https://github.com/stephenplusplus/grunt-bower-install

1
请注意,grunt-bower-install已更名为grunt-wiredep:https://github.com/stephenplusplus/grunt-wiredep - Stephen

4

使用 --save

bower install --save <YOUR_PACKAGE>

--save选项会更新bower.json文件中的依赖项。这将使您无需手动将其添加到bower.json中。您会发现,在index.html底部的脚本部分已经自动更新。参考:http://yeoman.io/codelab/install-packages.html

这绝对是正确的做法。它的工作方式与“npm --save”选项相同,并将其添加到package.json中。 - petur
4
您的理解是正确的,这会更新 bower.json 文件,但不会更新 index.html 文件。请注意,教程要求在检查 index.html 文件之前运行 grunt serve 命令。grunt serve 命令调用了 wiredep,这就是注入依赖项的魔力所在。 - Eric Grunzke
1
我使用这个来添加angular-jqcloud包,它会自动在我的index.html中创建jqcloud的脚本条目。 - pbnelson

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