Search code examples
typescriptgrunt-ts

Output emitted JS files from referenced TS files into single folder, without subfolders


I have a TypeScript file with a reference; the referenced file in turn has other references. When I run the grunt-ts task, a hierarchy of subfolders is created, mirroring the reference hierarchy, and each corresponding JS file is written into a scripts subfolder (apparently from the value of the outDir option). How can I configure the task so all the emitted JS files end up in a single subfolder?

My configuration looks like this:

grunt.initConfig({
    ts: {
        default: {
            src: ['**/*.ts', "!node_modules/**/*.ts"],
            noImplicitAny: true,
            sourceMap: true,
            target: 'es3',
            fast: 'always',
            outDir: 'scripts'
        }
    }
});

I tried specifying an absolute path for outDir with the same result.

If I don't specify outDir, the JS from referenced TS files is emitted in the location of the TS files, which could be outside the project folder.


Solution

  • Using the flatten option should do the trick:

    Output first to a temporary folder:

    ts: {
        default: {
            src: ['**/*.ts', "!node_modules/**/*.ts"],
            noImplicitAny: true,
            sourceMap: true,
            target: 'es3',
            fast: 'always',
            outDir: 'scripts-temp'
        }
    }
    

    Then use grunt-contrib-copy to copy and flatten your intermediate output to your final destination.

    copy: {
        default: {
            expand: true,
            cwd: 'scripts-temp/',
            src: '**',
            dest: 'scripts/',
            flatten: true,
            filter: 'isFile',
        },
    }
    

    Finally, use grunt-contrib-clean to delete the temporary folder:

    clean: {
        default: ['scripts-temp']
    }