给出命令Grunt时出错

时间:2013-06-28 14:43:26

标签: json gruntjs

我开始探索Grunt。阅读几个网站,我看到了一些例子。好吧,我创建了package.json和Gruntfile.js:

package.json http://pastebin.com/Kkt8fuXJ

Gruntfile.j http://pastebin.com/LnSmTzXZ

我项目文件夹的组织是:

root (index.html)
-src (where is package.json and Gruntfile.js)
-lib
 --css
  ---min
 --js
 --img

当我发出命令时,grunt总是会发生这个错误:

Loading "Gruntfile.js" tasks...ERROR
>> Error: Unable to parse "package.json" file (Unexpected token }).
Warning: Task "default" not found. Use --force to continue.

Aborted due to warnings.

如果我删除pkg:grunt.file.readJSON('package.json'),:

        grunt.loadNpmTasks('grunt-contrib-imagemin');
        ^^^^^
Loading "Gruntfile.js" tasks...ERROR
>> SyntaxError: Unexpected identifier
Warning: Task "default" not found. Use --force to continue.

Aborted due to warnings.

有什么问题?

由于

1 个答案:

答案 0 :(得分:5)

第一个错误是由package.json无效的JSON引起的。据我所知,你在第9行末尾使用了一个不必要的逗号。有效的JSON就是这样:

{
  "name": "EREBD",
  "description": "Site do evento EREBD XVII",
  "version": "1.0.0",
  "main": "Gruntfile.js",
  "dependencies": {
    "grunt": "~0.4.1",
    "grunt-contrib-cssmin": "~0.6.1",
    "grunt-contrib-imagemin": "~0.1.4"  //<- no comma there
  }
}

但是你甚至不需要在Gruntfile中导入package.json,因为你还没有使用它的任何属性。那你的Gruntfile有什么问题?那么你正在加载你的npm任务并在导出函数之外定义你的grunt任务。这就是正确的方式:

module.exports = function(grunt) {
    grunt.initConfig({
        // image optimization
        imagemin: {
            dist: {
                options: {
                    optimizationLevel: 4,
                    progressive: true
                },
                files: [{
                    expand: true,
                    cwd: '../lib/img/',
                                        src: '**/*',
                    dest: '../lib/img/'
                }]
            }
        },
        // minify css
        cssmin: {
                minify: {
                    expand: true,
                    src: ['../lib/css/*.css'],
                    dest: '../lib/css/min/',
                    ext: '.min.css'
                }
        }
    });

    // load tasks
    grunt.loadNpmTasks('grunt-contrib-imagemin');
    grunt.loadNpmTasks('grunt-contrib-cssmin');

    // extra tasks

    // register task
    grunt.registerTask('default', [
        'imagemin',
        'cssmin'
    ]);
};