javascript - 无法在 grunt 插件中写入 "undefined"文件

标签 javascript gruntjs npm

我是编写 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/

相关文章:

javascript - 多个输入的验证 | HTML-jQuery

javascript - 是否可以限制仅在 2 个脚本文件之间共享全局变量?

javascript - ExtJs 在 ENTER 按键上模拟 TAB

javascript - 如何使用 Grunt.js (0.3.x) 连接和缩小多个 CSS 和 JavaScript 文件

npm - 如何使用 `node2nix` 设置 NPM 命令行标志?

javascript - 如何在标签文本更改时触发事件

javascript - 在目录中查找文件,扫描其他目录文件并替换所有出现的文件名

javascript - Grunt 只会创建一个文件,不会创建多个文件

javascript - 语义版本控制 (Semver) - 如何对向后兼容的大型功能更新进行 semver

git - 每次更新通过 git 可用的包时,我是否需要发布到 npm?