Include all javascript files in a directory to a html file in angularjs? with grunt?

前端 未结 3 2090
时光取名叫无心
时光取名叫无心 2020-12-14 16:37

In my AngularJS app, I\'ve many controllers js files.

These controllers (one.ctrl.js,two.ctrl.js,...) needs to be included in

3条回答
  •  温柔的废话
    2020-12-14 17:30

    Answering the general question of adding source files to index.html on demand and automatically and elaborating on the use of grunt-include-source.

    This is for the following folder structure:

    MyProject
    |
    +-- index.js
    +-- Gruntfile.js
    +-- package.json
    +-- //other files
    |
    +--+ app
       +-- //app files (.html,.js,.css,.*)
    
    1. Install with npm i -D grunt-include-source grunt-contrib-watch.

    2. In your Gruntfile.js, add grunt.loadNpmTasks('grunt-include-source');

    3. Then you have to add a bunch of tasks to your Gruntfile.js, after which it should look like this:

      module.exports = function (grunt) {
          grunt.initConfig({
              pkg: grunt.file.readJSON('package.json'),
              //...
              watch: {
                  //...
                  includeSource: {
                      // Watch for added and deleted scripts to update index.html
                      files: ['app/**/*.js','app/**/*.css'],
                      tasks: ['includeSource'],
                      options: {
                          event: ['added', 'deleted']
                      }
                  }
              },
              includeSource: {
                  options: {
                      //This is the directory inside which grunt-include-source will be looking for files
                      basePath: 'app'
                  },
                  app: {
                      files: {
                          //Overwriting index.html
                          'app/index.html': 'app/index.html'
                      }
                  }
              }
          });
      
          //...
          grunt.loadNpmTasks('grunt-contrib-watch');
          grunt.loadNpmTasks('grunt-include-source');
      
          //...
          //Include sources, run the server, open the browser, and watch.
          grunt.registerTask('default', ['includeSource', 'watch']);
      };
      
    4. In your index.html, add this (the file path here looks inside the base path set in Gruntfile.js):

      
      
      
      
      
    5. Finally, on the command line:

      grunt
      

    This should start off all tasks in sequence, and your index.html should be updated accordingly when a JS or CSS is added or removed.

    This is how your index.html might look like with a small number of files:

    
    
    
    
    
    
    
    

    Links:

    • https://www.npmjs.com/package/grunt-include-source
    • https://ajsblackbelt.wordpress.com/2014/07/07/free-from-include/
    • https://jhipster.github.io/tips/002_tip_include_js_grunt.html

提交回复
热议问题