我是编写 grunt 插件的新手,在尝试运行它时遇到了问题:
Running "inject_css:dev" (inject_css) task
Warning: Unable to write "undefined" file (Error code: undefined). Use --force to continue.
我的插件看起来像:
'use strict';
module.exports = function(grunt) {
grunt.registerMultiTask('inject_css', 'Allows you to inject CSS into HTML files as part of the build process.', function() {
var src = grunt.file.expand(this.data.src);
var text = '';
if (src) {
src.forEach(function (script) {
text += grunt.file.read(script);
});
} else {
grunt.log.error('Please specify a file to inject into the html.');
return;
}
this.files.forEach(function (file) {
grunt.file.write(file.dest, grunt.file.read(file.src).replace('<!-- inject -->', '<style type="text/css">' + text + '</style>'));
grunt.log.ok('File injected'.blue + ' into ' + file.dest);
});
});
};
当尝试在我的 gruntfile 中调用它时,我使用了以下配置:
inject_css: {
dev: {
files:{
'static/test/test.html': 'test.html'
},
src: 'static/less/form.less'
}
}
知道我做错了什么吗?
最佳答案
看警告,我猜它是扔在那里的:
grunt.file.write(file.dest, grunt.file.read(file.src).replace('<!-- inject -->', '<style type="text/css">' + text + '</style>'));
这意味着 file.dest
是未定义的。
看看你的代码,这似乎是正常的,因为你在 this.files
上使用了一个 foreach,它不包含任何 dest
属性。
基本上,我认为您忘记展开 this.dest
并且这应该可以解决问题:
var expandedFiles = grunt.file.expand(this.data.files);
expandedFiles.forEach(function (file) {
grunt.file.write(file.dest, grunt.file.read(file.src).replace('<!-- inject -->', '<style type="text/css">' + text + '</style>'));
grunt.log.ok('File injected'.blue + ' into ' + file.dest);
});
因为我不能真正尝试,这只是一个猜测,如果它工作正常,请告诉我。
关于javascript - 无法在 grunt 插件中写入 "undefined"文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24335546/