如何在AngularJS中使用Grunt将一个目录中的所有JavaScript文件包含到HTML文件中?

24

在我的AngularJS应用程序中,我有许多控制器JS文件。

这些控制器(one.ctrl.jstwo.ctrl.js...)需要包含在我的index.html文件中。

目录结构:

app/
   js/
      controllers/
         one.ctrl.js
         two.ctrl.js

目前,js文件如下所示被包含在index.html文件中。

index.html:

<!--   other html components   -->

<script src="js/controllers/one.ctrl.js"/>
<script src="js/controllers/two.ctrl.js"/>
</body>
</html>

将会有更多的*.ctrl.js文件需要包含在index.html中。

我需要一种自动将controllers目录中的所有*.ctrl.js文件包含到index.html中的方法。

研究结果:

从一些stackoverflow问题中,

在AngularJS中加载文件夹中的JavaScript和CSS文件

如何通过Javascript文件包含目录中的所有JavaScript文件?

我发现这不能自动完成,需要一些服务器端脚本或构建工具。

我的问题:

目前,我正在使用yeoman,其中包括grunt作为构建工具。 因此,我的问题是,如何自动将目录中的javascript文件包含在html文件中?


我可以给你一个使用gulp.js的例子,可以吗? - Verron Knowles
我没有使用过 gulp.js。如果它能胜任工作,我可以尝试一下。 - TheKojuEffect
3个回答

13

你可以使用 grunt-include-source 插件。

使用这个插件,你可以像这样定义模板:

html: {
    js: '<script src="{filePath}"></script>',
    css: '<link rel="stylesheet" type="text/css" href="{filePath}" />',
  }

在您的HTML文件中,将展开包含源JS和CSS文件的所有内容,这些文件位于源位置中,可以在Grunt任务中进行配置。


你能提供一个完整的 Gruntfile.js 文件吗? - Jerome2606

7

回答如何按需自动地将源文件添加到index.html并详细介绍grunt-include-source的使用。

这适用于以下文件夹结构:

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):

    <!-- include: "type": "css", "files": "**/*.css" -->
    <!-- /include -->
    <!-- include: "type": "js", "files": "**/*.js" -->
    <!-- /include -->
    
  5. Finally, on the command line:

    grunt
    

这应该按序开始所有任务,当添加或删除JS或CSS文件时,您的index.html文件应相应更新。

以下是一些文件较少时,您的index.html可能会像这样:

<!-- include: "type": "css", "files": "**/*.css" -->
<link href="styles.css" rel="stylesheet" type="text/css">
<!-- /include -->
<!-- include: "type": "js", "files": "**/*.js" -->
<script src="_routes/routes.js"></script>
<script src="scripts/app.js"></script>
<!-- /include -->

链接:


1
你可以使用类似这样的代码:

您可以使用以下代码:

(function loadScript() {
    var head = document.getElementsByTagName("head")[0];
    var done = false;

    var directory = 'libraries/';
    var extension = '.js';
    var files = ['functions', 'speak', 'commands', 'wsBrowser', 'main']; 

     for (var file of files){ 
        var path = directory + file + extension; 
        var script = document.createElement("script");
        script.src = path;

        script.onload = script.onreadystatechange = function() {
        // attach to both events for cross browser finish detection:
        if ( !done && (!this.readyState ||
           this.readyState == "loaded" || this.readyState == "complete") ) {
           done = true;
           // cleans up a little memory:
           script.onload = script.onreadystatechange = null;
           // to avoid douple loading
           head.removeChild(script);
        }
    };
  head.appendChild(script); 
  done = false;
 }
})();

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