使用Grunt自动将本地*.js和*.css文件引用到index.html中

5
我打算开发一个AngularJS客户端,其中我将使用Angular组件。这将导致多个.js/.css文件。 为了避免手动引用每个新添加的js/css文件,我打算使用grunt-include-source任务。
问题在于,在配置Gruntfile.js后,“grunt includeSource”任务运行,返回“完成,无错误。”状态,但在index.html文件中没有进行更新。
我的项目结构如附图所示(我使用WebStorm作为IDE)。 Project structure 我的index.html文件如下:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>RavenApp</title>
    <!-- include: "type": "css", "files": "*.css" -->
</head>
<body>
    <!-- bower:js -->
    <script src="../bower_components/angular/angular.js"></script>
    <script src="../bower_components/angular-route/angular-route.js"></script>
    <script src="../bower_components/angular-sanitize/angular-sanitize.js"></script>
    <script src="../bower_components/angular-mocks/angular-mocks.js"></script>
    <script src="../bower_components/jquery/dist/jquery.js"></script>
    <script src="../bower_components/underscore/underscore.js"></script>
    <!-- endbower -->

    <!-- include: "type": "js", "files": "*.js" -->
</body>
</html>

我的Gruntfile.js文件如下:

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

    grunt.initConfig({
        wiredep: {
            target: {
                src: 'app/index.html'
            }
        },
        includeSource: {
            options: {
                basePath: 'app',
                templates: {
                    html: {
                        js: '<script src="{filePath}"></script>',
                        css: '<link rel="stylesheet" type="text/css" href="{filePath}" />'
                    }
                },
                app: {
                    files: {
                        'app/index.html': 'app/index.html'
                    }
                }
            }
        }
    });
};

请问有人能指出我做错了什么吗?谢谢。


1
appoptions 中移出到你的 gruntfile.js 外部。 - cartant
确实,那就是问题所在。现在它可以工作了,非常感谢。 - Lucian Bredean
1个回答

0

我们不需要在includeSource键下编写templates键:

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

grunt.initConfig({
    wiredep: {
        target: {
            src: 'app/index.html'
        }
    },
    includeSource: {
        options: {
            basePath: 'app',                
            app: {
                files: {
                    'app/index.html': 'app/index.html'
                }
            }
        }
    }
});
};

使用HTML代码即可包含JS和CSS:

 <!-- include: "type": "css", "files": "*.css" -->
 <!-- include: "type": "js", "files": "*.js" -->

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