这是我正在寻找的示例:
module.exports = function(grunt) {
grunt.initConfig({
config: grunt.file.readYAML('_config.yml'),
// example variable: <%= config.scripts %>
copy: {
scripts: (function() {
if (config.scripts === true) { // I want to target <%= config.scripts %>
return {
expand: true,
cwd: '<%= input %>/_assets/js/',
src: '**/*.js',
dest: '<%= output %>/assets/js/'
};
} else {
return {
// do nothing
};
}
})()
}
});
};
我知道 Grunt 可以使用“grunt.file.readJSON”从文件中读取数据,然后使用以下类型的变量“<%= pkg.value %>”获取该数据。
我想要做的是根据 JSON 文件中的变量创建一个带有 if/else 选项的任务。我不清楚的是如何以它理解的方式将 Grunt 变量 '<%= pkg.value %>' 传递到 JavaScript if 语句中。我试过以与“<%= %>”相同的 Grunt 格式传递它,以及剥离该部分并传递“pkg.value”,但似乎都不起作用。
如果有人能阐明这是否可以完成以及如何完成,我将不胜感激。谢谢!
最佳答案
与其直接在 config
属性中分配 grunt 配置,不如将其存储在变量 (gruntConfig
) 中。现在您将能够在以下代码中访问它。
module.exports = function(grunt) {
// store your grunt config
var gruntConfig = grunt.file.readYAML('_config.yml');
// init `script` with an empty object
var script = {};
if (gruntConfig.script) {
script = {
expand: true,
cwd: '<%= input %>/_assets/js/',
src: '**/*.js',
dest: '<%= output %>/assets/js/'
};
}
// Init Grunt configuration
grunt.initConfig({
config: gruntConfig,
copy: {
scripts: script
}
});
};
关于javascript - 你能在 Grunt 任务中将 Grunt 变量传递给 JavaScript 函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34552042/