![](/img/trans.png)
[英]How can I replace the variable which is in test.js file from gruntfile?
[英]How to get a variable from another file in gruntfile
我是新来的grunt
。
我的要求是,我需要根据另一个文件上设置的变量对文件进行丑化处理。
假设我有一些abc.js
文件,其中有一个变量var is_uglify = true;
我需要读取gruntfile中变量的值并相应地执行构建。
如果variable为true
,则需要执行以下操作:
grunt.registerTask('build', ['clean:build','uglify']);
除此以外
grunt.registerTask('build', ['clean:build']);
有人能帮忙吗?
这可以通过以下方式实现:
定义自定义任务 -即以下要点中的getValue
。
在getValue
任务/功能利用grunt.file.read获得的内容abc.js
。
然后使用正则表达式匹配分配给变量is_uglify
的布尔值。
一旦获得了is_uglify
的布尔值,就可以使用grunt.task.run有条件地运行名为buildA
或buildB
的已注册任务。
Gruntfile.js
以下要点显示了如何实现此目的:
module.exports = function (grunt) {
'use strict';
grunt.initConfig({
uglify: {
// ... <-- Define as necessary.
},
clean: {
build: {
//... <-- Define as necessary.
}
}
});
grunt.registerTask('getValue', 'Gets the value of a variable', function () {
var filepath = "path/to/abc.js", // <-- Define as necessary.
content = grunt.file.read(filepath),
value = content.match(/(?:var is_uglify = )(true|false);/);
if (!value) {
grunt.fail.warn(
'\'var is_uglify = [true|false];\' not found in: ' + filepath['yellow']
)
}
if (value[1] === 'true') {
grunt.task.run(['buildA']);
} else {
grunt.task.run(['buildB']);
}
});
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.registerTask('build', ["getValue"]);
grunt.registerTask('buildA', ['clean:build','uglify']);
grunt.registerTask('buildB', ['clean:build']);
};
补充笔记
"path/to/abc.js"
部分。 这必须是包含var is_uglify = ...;
文件的路径var is_uglify = ...;
: var filepath = "path/to/abc.js",
regex模式/(?:var is_uglify = )(true|false);/
可以在这里找到。 它将仅在abc.js
找到第一个匹配abc.js
。
如果缺少is_uglify
变量,则getValue
任务/功能将发出警告,并且任务/功能仅会失败并提早返回。
定义uglify
和clean:build
的配置后,通过CLI运行$ grunt build
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.