使配置更改对后续任务可见

Making a config change visible to subsequent tasks

使用:G运行t 1.01,load-g运行t-config,jit-g运行t.

我正在寻找一种简单的方法来设置 development/production 标志,以便在某些 G运行t 任务中使用。

第一个需要标志的任务是 webpack.js,以便在 React 的开发和生产构建之间切换。这是该文件:

module.exports = function( grunt ) {

    // Get the task that was invoked from the command line.
    var theTask = process.argv[2];

    // Check to see if it's a production task. If so, change the
    // `env` variable accordingly.
    if ( theTask !== undefined && theTask.indexOf('prod') === 0 ) {
        grunt.config.set('env', 'production');
    }

    return {
        app: {
            entry: './<%= siteInfo.build_dir %>/<%= siteInfo.temp_dir %>/<%= siteInfo.app_dir %>/<%= siteInfo.app_file %>.js',
            output: {
                path: '<%= siteInfo.build_dir %>/<%= siteInfo.temp_dir %>',
                filename: '<%= siteInfo.bundle_file %>.tmp.js'
            },
            stats: false,
            failOnError: true,
            progress: false,
            plugins: [
              new webpack.DefinePlugin({
                'process.env.NODE_ENV': JSON.stringify(grunt.config.data.env)
              }),
            ]
        }
    }

};

在这个任务的上下文中,它工作得很好。如果我 运行 grunt prod 那么正确版本的 React 被包含在捆绑的 JS 中。

然而,我有一个(肯定是)错误的印象,即通过使用 grunt.config.set 设置 env 变量,这个对 G运行t 的配置对象的更新将可以用于后续任务。

据我所知,如果我在另一项任务中 console.log(grunt.config.data.env)env 就是 undefined

感谢任何替代方法的指示或建议!

不要返回配置,试试这个:

创建预构建任务,在 运行 执行任务之前设置任何 config/options。您可以通过检查 this.name 来检查任务是否为 prod,然后因为它是一个简单的值,所以使用 grunt.option 设置它:

function preBuild() {

    grunt.option('env', this.name === 'prod' ? 'production' : 'development');
    grunt.task.run(['task1', 'task2', task3']);
}

grunt.registerTask('prod', preBuild);
grunt.registerTask('dev', preBuild);

使用 lo-dash 模板,您可以将选项值传递给您的配置。当访问它的任务是 运行:

时,G运行t 编译 lo-dash 模板字符串
grunt.initConfig({
    app: {
        entry: './<%= siteInfo.build_dir %>/<%= siteInfo.temp_dir %>/<%= siteInfo.app_dir %>/<%= siteInfo.app_file %>.js',
        output: {
            path: '<%= siteInfo.build_dir %>/<%= siteInfo.temp_dir %>',
            filename: '<%= siteInfo.bundle_file %>.tmp.js'
        },
        stats: false,
        failOnError: true,
        progress: false,
        plugins: [
          new webpack.DefinePlugin({
            'process.env.NODE_ENV': "<%= grunt.option('env') %>"
          }),
        ]
    }
});