URL87 URL87 - 6 months ago 104
Node.js Question

grunt-include-source doesn't work

I try to make a simple using of - grunt-include-source but I don't success -

My Gruntfile is -

module.exports = function (grunt) {
grunt.initConfig({
includeSource: {
options: {
basePath: 'app/file1.js'
},
myTarget: {
files: {
'dist/index.html': 'app/index.html'
}
}
}
});
grunt.loadNpmTasks('grunt-include-source');
grunt.registerTask('serve', function (target) {
grunt.task.run('includeSource');
});
}


The index.html is -

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


My folder hierarchy is -

Gruntfile.js
app >
file1.js
index.html
dist >
index.html


I run
grunt serve
and get in the
dist>index.html
folder the output -

<html>
<head>
</head>
<body>

</body>
</html>


Without the expected -
<script src="scripts/file1.js"></script>


I kept to follow as in the documentation and in this question ,

Why I don't get the expected output ?

Answer

You have two problems with your code, first in gruntfile you are specifying a wrong path, second on your html you are specifying a wrong source.

Let's go by parts, on your gruntfile you have this:

...
  includeSource: {
    options: {
      basePath: 'app/file1.js'
    },
...

The basepath option on the docs says:

Type: String or Array[String] Default value: ''

The base path to use when expanding files. Can be an array to support expanding files from multiple paths.

What this allows us to do is including one or more paths as our base path for our scripts. So let's change our basePath to basePath: 'app', our Gruntfile.js will look like this:

module.exports = function (grunt) {
  grunt.initConfig({
    includeSource: {
      options: {
        basePath: 'app'
      },
      myTarget: {
        files: {
          'dist/index.html': 'app/index.html'
        }
      }
    }
  });
  grunt.loadNpmTasks('grunt-include-source');
  grunt.registerTask('serve', function (target) {
    grunt.task.run('includeSource');
  });
};

Now if we run grunt serve it won't work, why? Well because on your index.html you have this:

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

Which means, insert script tags for all the javascript files, inside the scripts folder, but we don't have any scripts folder, so that's why your dist/index.html is empty. Let's change our index.html to this:

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

Run grunt serve et voilĂ  your index.html has changed to:

<html>
<head>
</head>
<body>
    <script src="file1.js"></script>
</body>
</html>

Now you just have to copy file1.js from app/ to dist/