How to include scripts automatically in a yeoman/grunt project?

柔情痞子 提交于 2019-11-27 04:22:43
Benjamin Crouzier

I used grunt-include-source

Install it:

npm install grunt-include-source --save-dev

In Gruntfile:

Load it before initConfig:

module.exports = function (grunt) {
  ...
  grunt.loadNpmTasks('grunt-include-source');

Configure includeSource itself in initConfig:

grunt.initConfig({
  ...,
  includeSource: {
      options: {
        basePath: 'app',
        baseUrl: '/',
      },
      server: {
        files: {
          '.tmp/index.html': '<%= yeoman.app %>/index.html'
        }
      },
      dist: {
        files: {
          '<%= yeoman.dist %>/index.html': '<%= yeoman.app %>/index.html'
        }
      }
    }

Add this task where you want (here, I add it to the build task):

grunt.registerTask('build', [
    'clean:dist',
    'includeSource:dist',
    'useminPrepare',
    ...

Add it to the watch task:

watch: {
  ...,
  includeSource: {
    files: ['<%= yeoman.app %>/index.html'],
    tasks: ['includeSource:server']
  }

Change useminPrepare (if you use yeoman)

useminPrepare: {
  // changed from app to dist, to take index.html processed by includeSource in dist
  html: '<%= yeoman.dist %>/index.html',
  options: {
    dest: '<%= yeoman.dist %>'
  }
},

I've used to subtasks: dist and server to generate the index.html in different directories.


Edit: How to include your javascripts in index.html:

<!-- build:js({.tmp,dist,app}) /scripts/application.js -->
<!-- vendor, external -->
<script src="/bower_components/jquery/jquery.min.js"></script>
<script src="/bower_components/underscore/underscore-min.js"></script>
<script src="/assets/vendor/underscore.extentions.js"></script>
<script src="/bower_components/angular/angular.js"></script>
<script src="/bower_components/select2/select2.js"></script>
<script src="/bower_components/angular-ui-select2/src/select2.js"></script>

<!-- entry point -->
<script src="/scripts/config.processed.js"></script>
<script src="/scripts/app.js"></script>

<!--include everything in scripts/ except files directly inside scripts (without subdirectory) -->
<!-- include: "type": "js", "files": ["scripts/**/*.js", "!scripts/*.js"] -->

<!-- endbuild -->

If you want to include everything scripts, do this:

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