Неустранимая ошибка: невозможно найти Gruntfile
grunt --version
grunt-cli v0.1.8
grunt v0.4.1
$npm -v
1.2.18
$node -v
v0.10.6
Когда я запускаю grunt init
для создания Gruntfile.js
, я получаю сообщение об ошибке:
$ grunt init
A valid Gruntfile could not be found. Please see the getting started guide for
more information on how to configure grunt: http://gruntjs.com/getting-started
Fatal error: Unable to find Gruntfile.
Я искал Grunfile.js, и я получаю:
/home/ka/.npm/grunt-cli/0.1.8/package/Gruntfile.js
/home/ka/tmp/npm-1464/1368671910572-0.38816986070014536/package/Gruntfile.js
/usr/local/lib/node_modules/grunt/Gruntfile.js
/usr/local/lib/node_modules/grunt/node_modules/findup-sync/Gruntfile.js
/usr/local/lib/node_modules/grunt-cli/Gruntfile.js
/usr/local/lib/node_modules/grunt-cli/node_modules/findup-sync/Gruntfile.js
/ex/co/www/dev/htdocs/unittest/node_modules/grunt/node_modules/findup-sync/Gruntfile.js
/ex/co/www/dev/htdocs/unittest/node_modules/grunt/Gruntfile.js
/root/.npm/findup-sync/0.1.2/package/Gruntfile.js
/root/.npm/grunt/0.4.1/package/Gruntfile.js
/root/.npm/grunt-cli/0.1.8/package/Gruntfile.js
Можно ли просто скопировать один из этих файлов grunt в /ex/co/www/dev/htdocs/unittest (где Javascript/квинт-тест)? Или есть что-то еще, что мне не хватает?
Я пытаюсь запустить grunt на Centos 6.4. Кроме того, почему grunt init
не создает Gruntfile.js
?
cp /root/.npm/grunt/0.4.1/package/Gruntfile.js /ex/co/www/dev/htdocs/unittest/
Я скопировал его AS-IS и теперь получаю лучшие ошибки:
grunt
>> Local Npm module "grunt-contrib-jshint" not found. Is it installed?
>> Local Npm module "grunt-contrib-nodeunit" not found. Is it installed?
>> Local Npm module "grunt-contrib-watch" not found. Is it installed?
Warning: Task "jshint" not found. Use --force to continue.
Aborted due to warnings.
прогресс режима.
grunt
Running "jshint:gruntfile" (jshint) task
Warning: Cannot call method 'forEach' of undefined Use --force to continue.
Aborted due to warnings.
[email protected] /ex/co/www/dev/htdocs/unittest $ grunt --force
Running "jshint:gruntfile" (jshint) task
Warning: Cannot call method 'forEach' of undefined Used --force, continuing.
Warning: Cannot call method 'forEach' of undefined Used --force, continuing.
Running "jshint:libs_n_tests" (jshint) task
Warning: Cannot call method 'forEach' of undefined Used --force, continuing.
Warning: Cannot call method 'forEach' of undefined Used --force, continuing.
Running "jshint:subgrunt" (jshint) task
Warning: Cannot call method 'forEach' of undefined Used --force, continuing.
Warning: Cannot call method 'forEach' of undefined Used --force, continuing.
Running "nodeunit:all" (nodeunit) task
Warning: Cannot call method 'map' of undefined Used --force, continuing.
Warning: Cannot call method 'map' of undefined Used --force, continuing.
Running "subgrunt:all" (subgrunt) task
Warning: Cannot read property 'length' of undefined Used --force, continuing.
Warning: Cannot read property 'length' of undefined Used --force, continuing.
Done, but with warnings.
My Gruntfile.js:
/*
* grunt
* http://gruntjs.com/
*
* Copyright (c) 2013 "Cowboy" Ben Alman
* Licensed under the MIT license.
* https://github.com/gruntjs/grunt/blob/master/LICENSE-MIT
*/
'use strict';
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
nodeunit: {
all: ['test/{grunt,tasks,util}/**/*.js']
},
jshint: {
gruntfile: ['Gruntfile.js'],
libs_n_tests: ['lib/**/*.js', '<%= nodeunit.all %>'],
subgrunt: ['<%= subgrunt.all %>'],
options: {
curly: true,
eqeqeq: true,
immed: true,
latedef: true,
newcap: true,
noarg: true,
sub: true,
undef: true,
unused: true,
boss: true,
eqnull: true,
node: true,
es5: true
}
},
watch: {
gruntfile: {
files: ['<%= jshint.gruntfile %>'],
tasks: ['jshint:gruntfile']
},
libs_n_tests: {
files: ['<%= jshint.libs_n_tests %>'],
tasks: ['jshint:libs_n_tests', 'nodeunit']
},
subgrunt: {
files: ['<%= subgrunt.all %>'],
tasks: ['jshint:subgrunt', 'subgrunt']
}
},
subgrunt: {
all: ['test/gruntfile/*.js']
},
});
// These plugins provide necessary tasks.
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-nodeunit');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-qunit');
grunt.registerTask('test', 'qunit:src');
// "npm test" runs these tasks
grunt.registerTask('test', ['jshint', 'nodeunit', 'subgrunt']);
// Default task.
grunt.registerTask('default', ['test']);
// Run sub-grunt files, because right now, testing tasks is a pain.
grunt.registerMultiTask('subgrunt', 'Run a sub-gruntfile.', function() {
var path = require('path');
grunt.util.async.forEachSeries(this.filesSrc, function(gruntfile, next) {
grunt.util.spawn({
grunt: true,
args: ['--gruntfile', path.resolve(gruntfile)],
}, function(error, result) {
if (error) {
grunt.log.error(result.stdout).writeln();
next(new Error('Error running sub-gruntfile "' + gruntfile + '".'));
} else {
grunt.verbose.ok(result.stdout);
next();
}
});
}, this.async());
});
};
Ответы
Ответ 1
Я думаю, что вы ищете фактический инструмент командной строки grunt-init
, найденный в документации Проектные леса.
Ваша текущая команда grunt init
ищет в ней Gruntfile.js
и задачу init
. Очевидно, что он не может найти ваш Gruntfile.js
, поэтому он бросает эту ошибку.
Edit:
Ваша новая ошибка связана с тем, что вы скопировали файл Gruntfile.js
, и задача default
(найденная внизу, если вы хотите ее открыть) будет вызывать эти модули. Обычно вы будете использовать что-то вроде bower
, чтобы установить их в свой локальный каталог.
Ваша задача по умолчанию, о которой я говорил выше, будет выглядеть примерно так:
grunt.registerTask('default', ['jshint', 'qunit', 'concat', 'uglify']);
В основном это говорит: когда я запускаю grunt
в командной строке, запустите задачи jshint
, qunit
, concat
и uglify
в этом порядке. Эти задачи будут указаны ранее в Gruntfile
. Чтобы понять файл, просмотрите образец Gruntfile.
Могу ли я предложить взглянуть на Yeoman, так как это отличный инструмент для предоставления вам лесов для ваших приложений (включая рабочий Gruntfile.js
).
Изменить 2:
Важно понимать, что происходит. Gruntfile.js
, который вы скопировали, выглядит так, что вы вызываете задачи "subgrunt". т.е. grunt
задачи в подпроектах. Это то, что вы хотите?
После вашего Gruntfile.js
- при запуске grunt
он вызывает следующий порядок: 'jshint', 'nodeunit', 'subgrunt'
.
В идеале вы хотите написать это самостоятельно, а не копировать его, так как есть некоторые опции, вызываемые jshint
Я незнаком с. Если вы читаете документацию jshint, она не упоминает первые три варианта.
Я думаю, вы должны попробовать что-то вроде этого:
jshint: {
options: {
curly: true,
eqeqeq: true,
immed: true,
latedef: true,
newcap: true,
noarg: true,
sub: true,
undef: true,
unused: true,
boss: true,
eqnull: true,
node: true,
es5: true
}
files: {
src: ['path/to/your/*.js', 'another/path/to/your/*.js']
}
}
Вы должны прочитать документацию по каждой задаче и убедиться, что вы понимаете параметры, которые вы проходите.
Еще один намек. Если вы видите ссылку на файл, как показано ниже:
<%= jshint.gruntfile %>
Это ссылка на конкретный файл/свойство, установленный в Gruntfile.js
. В этом случае это произошло из задачи watch
и указывает на свойство jshint.gruntfile
в качестве файла для просмотра.
Ответ 2
У меня была такая же ошибка, и оказалось, что мне просто нужно сначала запустить npm install. Хотя я уже установил npm ранее, что-то стало поврежденным с установкой. Была произведена быстрая переустановка; Все, что мне было нужно, это две команды:
npm install
grunt jshint
Ответ 3
У меня была аналогичная проблема, я использовал приведенные ниже команды, и это сработало для меня
grunt -f
grunt server
Надеюсь, что это сработает и для вас.
Ответ 4
Файл Grunt должен находиться в корневом каталоге, а не в какой-либо папке, также он должен содержать "Gruntfile.js".
Пример
В случае angular проекта asp.net Core его местоположение должно быть.
![enter image description here]()
Это не будет работать, если вы поместите этот файл в ClientApp или где-то еще, пока не определите какой-либо метод для этого.
Ответ 5
проверьте, находитесь ли вы на dirctory, над которым работаете, и
запустите npm install там, он, вероятно, решит вашу проблему.