2016-02-12 101 views
1

我在自定義grunt任務中遇到錯誤。下面我發佈有關該問題的簡單測試案例:錯誤「Object has no method'endsWith'」on custom grunt task

Gruntfile.js

module.exports = function(grunt){ 

    grunt.task.registerTask('endsWith', 'Test of string.prototype.endsWith', function(){ 
     var value = grunt.option('value'); 
     grunt.log.writeln(typeof value); 
     grunt.log.writeln(value.endsWith('bar')); 
    }) 

}; 

測試

> grunt endsWith --value=foobar 
Running "endsWith" task 
string 
Warning: Object foobar has no method 'endsWith' Use --force to continue. 

Aborted due to warnings. 

Execution Time (2016-02-12 16:15:19 UTC) 
Total 12ms 

這就像咕嚕不承認String.proptotype.endsWith功能。這是正常的嗎?

編輯:我使用節點v0.10.4

+0

node'您運行的是什麼版本的'? (運行'node -v'來查找) –

回答

5

.endsWith is an ES6 feature,並沒有在Node.js的v0.10.4實現。

要使用.endsWith要麼升級的Node.js或add in a polyfill

String.prototype.endsWith = function(suffix) { 
    return this.indexOf(suffix, this.length - suffix.length) !== -1; 
}; 
0

如果你是在舊的版本,你可以使用String.match方法節點。

更換

grunt.log.writeln(value.endsWith('bar')); 

grunt.log.writeln(value.match("bar$")); 

完整代碼

module.exports = function(grunt){ 

    grunt.task.registerTask('endsWith', 'Test of string.prototype.endsWith', function(){ 
     var value = grunt.option('value'); 
     grunt.log.writeln(typeof value); 
     grunt.log.writeln(value.match("bar$")); 
    }) 

}; 
相關問題