Bower+grunt-wiredep自动注入包到html

以安装jquery为例

1、假设已经通过npm安装好了bower和grunt-wiredep,以及grunt-contrib-watch(用来观察文件变动)

在gruntfile.js文件中增加任务

wiredep: {
      target: {
        src:['public/index.html'] //指定要将bower下载的包添加到的html文件
      }
    }
2、在watch中观察bower.json文件,如果该文件变动,则执行wiredep任务,将下载的包插入html

watch: {
      gruntfile: {
        files: '<%= jshint.gruntfile.src %>',
        tasks: ['jshint:gruntfile']
      },
      lib_test: {
        files: '<%= jshint.lib_test.src %>',
        tasks: ['jshint:lib_test', 'qunit']
      },
      bower: {                 //为观察bower.json
        files: ['bower.json'],
        tasks: ['wiredep']
      }

    }
3、加载包,并设为默认启动
grunt.loadNpmTasks('grunt-wiredep');

  // Default task.
  grunt.registerTask('default', ['jshint','concat', 'uglify','wiredep', 'watch']);
4、指定包在html的插入位置,在html文件中添加注释,包会被插入到注释中

  <!-- bower:js -->  js插入位置
  <!-- endbower -->

  <!-- bower:css --> css插入位置
  <!-- endbower -->

5、在控制台输入命令运行grunt

grunt

6、另打开一个控制台,下载jquery,运行以下命令

bower install jquery --save
可以看到bower.json如下

"dependencies": {
    "socket.io-client": "^2.0.1",
    "bootstrap": "^3.3.7",
    "jquery": "^3.2.1"
  }
index.htm自动插入了jquery

<!-- bower:js -->
    <script src="../bower_components/jquery/dist/jquery.js"></script>
    <script src="../bower_components/bootstrap/dist/js/bootstrap.js"></script>
<!-- endbower -->









posted @ 2017-05-18 15:13  zc的救赎  阅读(223)  评论(0)    收藏  举报