简体   繁体   中英

node.js: include external grunt configuration

I have a grunt file at a top level directory, I would like to include configuration settings that are in sub-folders. Is there a clean way to do this with grunt?

Put them in JSON files and import them using grunt.file.readJSON .

Example:

module.exports = function (grunt) {
    grunt.initConfig({
        settings: grunt.file.readJSON('subfolder/settings.json'),
        settings2: grunt.file.readJSON('subfolder2/settings.json'),
        task: {
            target: {
                files: {
                    'dest': '<%- settings.path %>',
                    'dest': '<%- settings2.path %>'
                }
            }
        }
    });
};

As an alternative you could use require . An example of this setup with different environments, with "concat" and "uglify" components.

Structure:

// root
Gruntfile.js
config/
    env1.js
    env2.js
src/
    file1.js
    file2.js
    ...

dest/
    env1.js
    env1.min.js
    env2.js
    env2.min.js

Files:

// Gruntfile.js ...
// ____________________> 
var config = {
    'env1' : require('./config/env1'),
    'env2' : require('./config/env2')
};
module.exports = function (grunt) {
    grunt.initConfig({
        concat: {
            env1: {
                src: config.env1, // ^config
                dest: 'dest/env1.js'
            },
            env2: {
                src: config.env2, // ^config
                dest: 'dest/env2.js'
            }
        },
        uglify: {
            my_target: {
                files: {
                    'dest/env1.min.js' : ['dest/env1.js'],
                    'dest/env2.min.js' : ['dest/env2.js']
                }
            }
        }
    });

    grunt.loadNpmTasks('grunt-contrib-concat');
    grunt.loadNpmTasks('grunt-contrib-uglify');

    grunt.registerTask('default', ['concat', 'uglify']);
};

// config/env1.js ...
// ____________________> 
module.exports = [
    // files...
    'src/file1.js',
    'src/file2.js',
    'src/file3.js'
];

// config/env2.js ...
// ____________________> 
module.exports = [
    // files...
    'src/file4.js',
    'src/file5.js',
    'src/file6.js'
];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM