Search code examples
javascriptreactjsgruntjsjsxgrunt-babel

Grunt Add multiple input/output directories


I am using grunt-babel to transform my react-jsx files into .js.

I am planning to write a grunt task for this. Currently, I have below

module.exports = function( grunt ) {
    require('load-grunt-tasks')(grunt);
    grunt.initConfig( {

        babel : {
            options : {
                plugins : ['transform-react-jsx'],
                presets: ['es2015', 'react']
            },
            client : {
                expand : true,
                cwd : './react_demo/test/jsx/common',
                src : ['*.jsx'],
                dest : './react_demo/static/react/components',
                ext : '.js'
            }
        }
    } );

    grunt.loadNpmTasks('grunt-babel');
    grunt.registerTask('default', ['babel:client']);

};

In my above task what I am trying to do is, I am transforming all my JSX files present in folder ./react_demo/test/jsx/common into ./react_demo/static/react/components.

Now, in my application in future we can have multiple folder each having there own-set of JSX files which will be going into different destination folders.

We can have folders like:

  • /react_demo/test/jsx/common -> /react_demo/static/react/components
  • /react/test/jsx/common1 -> /react/static/react/components1
  • /react2/test/jsx/common2 -> /react2/static/react/components2

Now, how can I specify multiple src/destdirectories and map them together? I tried giving an array to src/dest but it complained with below error:

Warning: Path must be a string. Received [ './react_demo/cartridge/scripts/jsx/common' ] Use --force to continue.


Solution

  • As far as I know you will have to specify a new babel target for each new destination:

    module.exports = function( grunt ) {
        require('load-grunt-tasks')(grunt);
        grunt.initConfig( {
    
            babel : {
                options : {
                    plugins : ['transform-react-jsx'],
                    presets: ['es2015', 'react']
                },
                client : {
                    expand : true,
                    cwd : './react_demo/test/jsx/common',
                    src : ['*.jsx'],
                    dest : './react_demo/static/react/components',
                    ext : '.js'
                },
                common1 : {//add more targets
                    expand : true,
                    cwd : './react/test/jsx/common1',
                    src : ['*.jsx'],
                    dest : './react/static/react/components1',
                    ext : '.js'
                }//etc..
    
            }
        } );
    
        grunt.loadNpmTasks('grunt-babel');
        grunt.registerTask('default', ['babel:client','babel:common1']);//reg new targets
    
    };