【问题标题】:Unable to write "undefined" file in grunt plugin无法在 grunt 插件中写入“未定义”文件
【发布时间】:2014-06-23 23:41:47
【问题描述】:

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

任何想法我做错了什么?

【问题讨论】:

    标签: javascript gruntjs npm


    【解决方案1】:

    看警告,我猜它是扔在那里的:

    grunt.file.write(file.dest, grunt.file.read(file.src).replace('<!-- inject -->', '<style type="text/css">' + text + '</style>'));
    

    这意味着file.dest 未定义。

    查看您的代码,这似乎很正常,因为您使用不包含任何 dest 属性的 this.files 上的 foreach。

    基本上,我认为您忘记扩展 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);
    });
    

    由于我无法真正尝试,这只是一个猜测,让我知道它是否工作正常。

    【讨论】:

      【解决方案2】:

      你试过了吗

      inject_css: {
        dev: {
          .....
          src: ['static/less/form.less']
        }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-11-04
        • 1970-01-01
        • 2014-03-23
        • 1970-01-01
        • 1970-01-01
        • 2018-06-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多