Grunt task: Compiling to a destination without preserving the folder structure

Grunt task: Compiling to a destination without preserving the folder structure

It is not uncommon to have a complex folder structure for scss or js files. When compiling with Grunt, the outputted file will maintain the same file path as the original. To change this behaviour use the flatten property.

Note:
I am using scss files for this example but the same is true for any other file.

Default behaviour

Here is the folder structure for our Sass files:

Content
+-- sass
|    +-- base
|    |   +-- _reset.scss
|    |   +-- _typography.scss
|    +-- components
|    |   +-- header
|    |   |   +-- _header.scss
|    |   +-- footer
|    |   |   +-- _footer.scss
|    +-- pages
|    |   +-- home
|    |   |   +-- home.scss
|    +-- utilities
|    |   +-- _icons.scss
|    |   +-- _mixins.scss

All files are under the sass folder and are further nested within a folder structure.

Here is an example of the Grunt configuration for Sass:

sass: {
    dist: {
        files: [
          {
              expand: true, // Recursive
              cwd: "Content/sass", // The startup directory
              src: ["**/*.scss"], // Source files
              dest: "Content/stylesheets", // Destination
              ext: ".css" // File extension 
          }
        ]
    }
}

Content/sass is set as the relative path. expand: true enables recursion and the output destination is Content/stylesheets. Using our example home.scss compiles to the stylesheets folder keeping the same file path.

Content
+-- stylesheets
|    +-- pages
|    |   +-- home
|    |   |   +-- home.css

Flattening the folder structure

Sometimes we may not want the same folder structure for the compiled files. To prevent this use the flatten property. The Grunt task documentation describes the functionality as.

Remove all path parts from generated dest paths.

Adding this to the configuration:

sass: {
    dist: {
        files: [
          {
              expand: true, // Recursive
              flatten: true,
              cwd: "Content/sass", // The startup directory
              src: ["**/*.scss"], // Source files
              dest: "Content/stylesheets", // Destination
              ext: ".css" // File extension 
          }
        ]
    }
}

Outputs the stylesheet as stylesheets\home.css.

Content
+-- stylesheets
|    +-- home.css

Summary

The flatten property is used when the file path of the original file is not needed for the outputted file. We can have a folder structure that adds meaning to our pre-compile files without retaining it in the output.