2016-05-24 7 views
0

Я работаю над сайтом Node.js, и я использую Grunt для конкат и минимизации моих CSS и JS-файлов. Тем не менее, после выполнения команды grunt Я получаю сообщение об ошибке:Grunt concats JS-файл несколько раз

fullPage: Fullpage.js can only be initialized once and you are doing it multiple times!

Вот мой пехотинец файл:

/*global module */ 
module.exports = function (grunt) { 
    "use strict"; 
    grunt.initConfig({ 
     // read in the project settings from the package.json file into the pkg property 
     pkg: grunt.file.readJSON("package.json"), 

     // Install only the bower packages that we need 
     bower: { 
      install: { 
       options: { 
        "targetDir": "./public/lib", 
        "copy": true, 
        "cleanup": true, 
        "install": true 
       } 
      } 
     }, 

     concat: { 
      css: { 
       src: ["public/lib/css/**/*.css", "public/css/cts.css"], 
       dest: "public/lib/dist/main.css" 
      }, 
      js: { 
       src: ["public/lib/**/jquery.js", "public/lib/**/*.js", "public/js/cts.js"], 
       dest: "public/lib/dist/main.js" 
      } 
     }, 

     cssmin: { 
      target: { 
       files: { 
        "public/lib/dist/main.min.css": "public/lib/dist/main.css" 
       } 
      } 
     }, 

     uglify : { 
      js: { 
       files: { 
        "public/lib/dist/main.min.js": "public/lib/dist/main.js" 
       } 
      } 
     }, 

     copy: { 
      files: { 
       expand: true, 
       flatten: true, 
       src: ["public/lib/fonts/**/*"], 
       dest: "public/lib/fonts/", 
       filter: "isFile" 
      } 
     } 
    }); 

    // Add all plugins that your project needs here 
    grunt.loadNpmTasks("grunt-bower-task"); 
    grunt.loadNpmTasks("grunt-contrib-concat"); 
    grunt.loadNpmTasks("grunt-contrib-copy"); 
    grunt.loadNpmTasks("grunt-contrib-cssmin"); 
    grunt.loadNpmTasks("grunt-contrib-uglify"); 
    grunt.loadNpmTasks("grunt-contrib-watch"); 

    // this would be run by typing "grunt test" on the command line 
    // the array should contains the names of the tasks to run 
    grunt.registerTask("test", []); 

    // define the default task that can be run just by typing "grunt" on the command line 
    // the array should contains the names of the tasks to run 
    grunt.registerTask("default", [ "bower", "concat", "cssmin", "uglify", "copy"]); 
    grunt.registerInitTask("install", ["bower"]); 
}; 

Если что-то я бы подумал, JQuery будет тот, который получает сцепляются много раз, но это не так. Любые предложения, что я могу делать неправильно?

EDIT: Вот мой обновленный файл grunt со всеми сторонними библиотеками, перечисленными в файле concat.src.

/// <binding BeforeBuild='default' /> 
/*global module */ 
module.exports = function (grunt) { 
    "use strict"; 
    grunt.initConfig({ 
     // read in the project settings from the package.json file into the pkg property 
     pkg: grunt.file.readJSON("package.json"), 

     // Install only the bower packages that we need 
     bower: { 
      install: { 
       options: { 
        "targetDir": "./public/lib", 
        "copy": true, 
        "cleanup": true, 
        "install": true 
       } 
      } 
     }, 

     concat: { 
      css: { 
       src: ["public/lib/css/**/*.css", "public/css/cts.css"], 
       dest: "public/lib/dist/main.css" 
      }, 
      js: { 
       src: [ 
        "public/lib/js/jquery/jquery.js", 
        "public/lib/js/bootstrap/bootstrap.js", 
        "public/lib/js/fullpage.js/jquery.fullpage.js", 
        "public/lib/js/jquery-easing-original/jquery.easing.js", 
        "public/lib/js/slimscroll/jquery.slimscroll.js", 
        "public/lib/js/wow/wow.js", 
        "public/js/cts.js" 
        ], 
       dest: "public/lib/dist/main.js" 
      } 
     }, 

     cssmin: { 
      target: { 
       files: { 
        "public/lib/dist/main.min.css": "public/lib/dist/main.css" 
       } 
      } 
     }, 

     uglify : { 
      js: { 
       files: { 
        "public/lib/dist/main.min.js": "public/lib/dist/main.js" 
       } 
      } 
     }, 

     copy: { 
      files: { 
       expand: true, 
       flatten: true, 
       src: ["public/lib/fonts/**/*"], 
       dest: "public/lib/fonts/", 
       filter: "isFile" 
      } 
     } 
    }); 

    // Add all plugins that your project needs here 
    grunt.loadNpmTasks("grunt-bower-task"); 
    grunt.loadNpmTasks("grunt-contrib-concat"); 
    grunt.loadNpmTasks("grunt-contrib-copy"); 
    grunt.loadNpmTasks("grunt-contrib-cssmin"); 
    grunt.loadNpmTasks("grunt-contrib-uglify"); 
    grunt.loadNpmTasks("grunt-contrib-watch"); 

    // this would be run by typing "grunt test" on the command line 
    // the array should contains the names of the tasks to run 
    grunt.registerTask("test", []); 

    // define the default task that can be run just by typing "grunt" on the command line 
    // the array should contains the names of the tasks to run 
    grunt.registerTask("default", [ "bower", "concat", "cssmin", "uglify", "copy"]); 
    grunt.registerTask("combine", [ "concat", "cssmin", "uglify", "copy"]); 
    grunt.registerInitTask("install", ["bower"]); 
}; 
+0

Есть ли конкретная причина, по которой путь jquery содержит подстановочные знаки? Кажется ненужным – theaccordance

+0

В этом проекте много людей, и вложенная структура может измениться. Подстановочные знаки помогают гарантировать, что это продолжает работать, пока файлы находятся где-то под 'public/lib /'. – tylerbhughes

ответ

1

Ваш вопрос, кажется, в concate.js.src

src: ["public/lib/**/jquery.js", "public/lib/**/*.js", "public/js/cts.js"] 

Это будет иметь ваши файлы добавлены несколько раз, как там может некоторые файлы распространенных среди путей, указанных в ИПВ.

Возможно, вы должны перенести все файлы вашего поставщика, такие как jquery, из общедоступного каталога и добавить другой, скажем, поставщика.

Ваш ЦСИ должен выглядеть примерно как

src: ["vendor/**/*.js", "public/**/*.js"] 

Как вы видите сейчас нет общих файлов между этими двумя путями.

Также его хорошая практика всегда иметь сторонний код вне вашего каталога приложений как папку для сиблинга, а не внутри него.

EDIT:

Ах! Я понимаю, в чем проблема. Вы хотите, чтобы jquery был первым среди других файлов поставщика.

public/lib/**/jquery.js и public/lib/**/*.js вместе могут быть причиной добавления файлов в два раза.

Попробуйте

src: ["public/lib/jquery/jquery.js", "public/lib/**/*.js", "!public/lib/jquery/jquery.js", public/js/cts.js"] 

Поместите полный путь JQuery первого public/lib/jquery/jquery.js, а затем !public/lib/jquery/jquery.js должен предотвратить JQuery добавляется снова как часть public/lib/**/*.js

Получили выше узор из здесь http://gruntjs.com/configuring-tasks#globbing-patterns

Если это все еще не работает, то другой вариант состоит в том, чтобы добавить все пути в массив src отдельно. Если у вас есть config requirejs, просто скопируйте пути оттуда, так как jquery может быть не единственной проблемой, с которой вы столкнетесь в будущем.

+0

Все файлы внутри public/lib/** 'являются только файлами поставщика.Вот почему у меня их есть в папке с lib. Единственная причина, по которой моя текущая конфигурация src не так проста, как ваша, заключается в том, что один из этих файлов является файлом Bootstrap JS, а jQuery должен быть добавлен первым, иначе он не будет работать. – tylerbhughes

+0

@RandomlyKnighted: Понял. Я отредактировал ответ. Посмотрите, помогает ли это – shinobi

+0

, после чего он сказал, что jQuery и один из моих других файлов поставщиков не были определены. Я прошел через и добавил все пути по отдельности, и я все еще получаю сообщение об ошибке, говоря, что это один из файлы поставщика инициализируются несколько раз. – tylerbhughes

 Смежные вопросы

  • Нет связанных вопросов^_^