Grunt удаляет скрипты и css в index.html

У меня есть приложение, развернутое на героку в течение некоторого времени. Я всегда добавляю компоненты, используя bower install, а затем ворчу, чтобы минимизировать, исказить и объединить.

Я использовал yoman для создания файла Gruntfile.js

Я установил новую библиотеку, включил ее в свой index.html и запустил команду grunt, она внезапно была удалена из моего index.html.

Слева — то, что происходит после запуска Grunt, справа — до запуска команды grunt

Различия файлов css удалены

Вот разница одного удаленного файла javascript файл javascript удален

Вот файл Bower.json

{
  "name": "civilization-web",
  "version": "0.0.0",
  "dependencies": {
    "lodash": "2.4.1",
    "angular": "~1.3.8",
    "json3": "~3.3.1",
    "es5-shim": "~3.1.0",
    "bootstrap": "~3.3.1",
    "angular-resource": "~1.3.7",
    "angular-sanitize": "~1.3.7",
    "angular-animate": "~1.3.7",
    "angular-touch": "~1.3.7",
    "angular-route": "~1.3.7",
    "angular-utf8-base64": "~0.0.5",
    "angular-messages": "~1.3.8",
    "ng-table": "~0.3.3",
    "angular-bootstrap": "~0.12.0",
    "ng-file-upload": "~2.0.5",
    "ng-file-upload-shim": "~2.0.5",
    "angular-growl-v2": "~0.7.3",
    "nya-bootstrap-select": "~2.0.8",
    "animate.css": "~3.2.6",
    "angular-bootstrap-simple-chat": "~0.3.1",
    "angularjs-scroll-glue": "~0.0.1"
  },
  "devDependencies": {
    "angular-mocks": "~1.3.7",
    "angular-scenario": "~1.3.7"
  },
  "appPath": "app",
  "resolutions": {
    "angular": "1.3.8"
  }
}

Вот мой GruntFile.js

// Generated on 2015-05-12 using generator-angular 0.11.1
'use strict';

// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'

module.exports = function (grunt) {

    // Load grunt tasks automatically
    require('load-grunt-tasks')(grunt);

    // Time how long tasks take. Can help when optimizing build times
    require('time-grunt')(grunt);

    // Configurable paths for the application
    var appConfig = {
        app: require('./bower.json').appPath || 'app',
        dist: 'dist'
    };

    // Define the configuration for all the tasks
    grunt.initConfig({

        // Project settings
        yeoman: appConfig,

        // Watches files for changes and runs tasks based on the changed files
        watch: {
            bower: {
                files: ['bower.json'],
                tasks: ['wiredep']
            },
            js: {
                files: ['<%= yeoman.app %>/scripts/{,*/}*.js'],
                tasks: ['newer:jshint:all'],
                options: {
                    livereload: '<%= connect.options.livereload %>'
                }
            },
            styles: {
                files: ['<%= yeoman.app %>/styles/{,*/}*.css'],
                tasks: ['newer:copy:styles', 'autoprefixer']
            },
            gruntfile: {
                files: ['Gruntfile.js']
            },
            livereload: {
                options: {
                    livereload: '<%= connect.options.livereload %>'
                },
                files: [
                    '<%= yeoman.app %>/{,*/}*.html',
                    '.tmp/styles/{,*/}*.css',
                    '<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
                ]
            }
        },

        // The actual grunt server settings
        connect: {
            options: {
                port: 9000,
                // Change this to '0.0.0.0' to access the server from outside.
                hostname: 'localhost',
                livereload: 35729
            },
            livereload: {
                options: {
                    open: true,
                    middleware: function (connect) {
                        return [
                            connect.static('.tmp'),
                            connect().use(
                                '/bower_components',
                                connect.static('./bower_components')
                            ),
                            connect().use(
                                '/app/styles',
                                connect.static('./app/styles')
                            ),
                            connect.static(appConfig.app)
                        ];
                    }
                }
            },
            dist: {
                options: {
                    open: true,
                    base: '<%= yeoman.dist %>'
                }
            }
        },

        // Make sure code styles are up to par and there are no obvious mistakes
        jshint: {
            options: {
                jshintrc: '.jshintrc',
                reporter: require('jshint-stylish')
            },
            all: {
                src: [
                    'Gruntfile.js',
                    '<%= yeoman.app %>/scripts/{,*/}*.js'
                ]
            }
        },

        // Empties folders to start fresh
        clean: {
            dist: {
                files: [{
                    dot: true,
                    src: [
                        '.tmp',
                        '<%= yeoman.dist %>/{,*/}*',
                        '!<%= yeoman.dist %>/.git{,*/}*'
                    ]
                }]
            },
            server: '.tmp'
        },

        // Add vendor prefixed styles
        autoprefixer: {
            options: {
                browsers: ['last 1 version']
            },
            server: {
                options: {
                    map: true,
                },
                files: [{
                    expand: true,
                    cwd: '.tmp/styles/',
                    src: '{,*/}*.css',
                    dest: '.tmp/styles/'
                }]
            },
            dist: {
                files: [{
                    expand: true,
                    cwd: '.tmp/styles/',
                    src: '{,*/}*.css',
                    dest: '.tmp/styles/'
                }]
            }
        },

        // Automatically inject Bower components into the app
        wiredep: {
            app: {
                src: ['<%= yeoman.app %>/index.html'],
                ignorePath:  /\.\.\//
            }
        },

        // Reads HTML for usemin blocks to enable smart builds that automatically
        // concat, minify and revision files. Creates configurations in memory so
        // additional tasks can operate on them
        useminPrepare: {
            html: '<%= yeoman.app %>/index.html',
            options: {
                dest: '<%= yeoman.dist %>',
                flow: {
                    html: {
                        steps: {
                            //js: ['concat', 'uglifyjs'],
                            js: ['concat'],
                            css: ['cssmin']
                        },
                        post: {}
                    }
                }
            }
        },

        // Performs rewrites based on filerev and the useminPrepare configuration
        usemin: {
            html: ['<%= yeoman.dist %>/{,*/}*.html'],
            css: ['<%= yeoman.dist %>/styles/{,*/}*.css'],
            options: {
                assetsDirs: [
                    '<%= yeoman.dist %>',
                    '<%= yeoman.dist %>/styles'
                ]
            }
        },


        imagemin: {
            dist: {
                files: [{
                    expand: true,
                    cwd: '<%= yeoman.app %>/images',
                    src: '{,*/}*.{png,jpg,jpeg,gif}',
                    dest: '<%= yeoman.dist %>/images'
                }]
            }
        },

        svgmin: {
            dist: {
                files: [{
                    expand: true,
                    cwd: '<%= yeoman.app %>/images',
                    src: '{,*/}*.svg',
                    dest: '<%= yeoman.dist %>/images'
                }]
            }
        },

        htmlmin: {
            dist: {
                options: {
                    collapseWhitespace: true,
                    conservativeCollapse: true,
                    collapseBooleanAttributes: true,
                    removeCommentsFromCDATA: true,
                    removeOptionalTags: true
                },
                files: [{
                    expand: true,
                    cwd: '<%= yeoman.dist %>',
                    src: ['*.html', 'views/{,*/}*.html'],
                    dest: '<%= yeoman.dist %>'
                }]
            }
        },

        // ng-annotate tries to make the code safe for minification automatically
        // by using the Angular long form for dependency injection.
        ngAnnotate: {
            dist: {
                files: [{
                    expand: true,
                    cwd: '.tmp/concat/scripts',
                    src: '*.js',
                    dest: '.tmp/concat/scripts'
                }]
            }
        },

        // Replace Google CDN references
        cdnify: {
            dist: {
                html: ['<%= yeoman.dist %>/*.html']
            }
        },

        // Copies remaining files to places other tasks can use
        copy: {
            dist: {
                files: [{
                    expand: true,
                    dot: true,
                    cwd: '<%= yeoman.app %>',
                    dest: '<%= yeoman.dist %>',
                    src: [
                        '*.{ico,png,txt}',
                        '.htaccess',
                        '*.html',
                        'views/{,*/}*.html',
                        'images/{,*/}*.{webp}',
                        'styles/fonts/{,*/}*.*'
                    ]
                }, {
                    expand: true,
                    cwd: '.tmp/images',
                    dest: '<%= yeoman.dist %>/images',
                    src: ['generated/*']
                }, {
                    expand: true,
                    cwd: 'bower_components/bootstrap/dist',
                    src: 'fonts/*',
                    dest: '<%= yeoman.dist %>'
                }]
            },
            styles: {
                expand: true,
                cwd: '<%= yeoman.app %>/styles',
                dest: '.tmp/styles/',
                src: '{,*/}*.css'
            }
        },

        // Run some tasks in parallel to speed up the build process
        concurrent: {
            server: [
                'copy:styles'
            ],
            dist: [
                'copy:styles',
                'imagemin',
                'svgmin'
            ]
        }
    });


    grunt.registerTask('serve', 'Compile then start a connect web server', function (target) {
        if (target === 'dist') {
            return grunt.task.run(['build', 'connect:dist:keepalive']);
        }

        grunt.task.run([
            'clean:server',
            'wiredep',
            'concurrent:server',
            'autoprefixer:server',
            'connect:livereload',
            'watch'
        ]);
    });

    grunt.registerTask('server', 'DEPRECATED TASK. Use the "serve" task instead', function (target) {
        grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.');
        grunt.task.run(['serve:' + target]);
    });

    grunt.registerTask('build', [
        'clean:dist',
        'wiredep',
        'useminPrepare',
        'concurrent:dist',
        'autoprefixer',
        'concat',
        'ngAnnotate',
        'copy:dist',
        'cdnify',
        'cssmin',
        //'uglify',
        'usemin',
        'htmlmin'
    ]);

    grunt.registerTask('default', [
        'newer:jshint',
        'build'
    ]);
};

Кто-нибудь знает, почему Grunt удаляет эти файлы, когда я запускаю Grunt?

PS: Мой код находится на github, вы можете просмотреть его там


person Shervin Asgari    schedule 01.10.2015    source источник
comment
Обе команды grunt serve и grunt удаляют файлы bootstrap.css и angular-bootstrap-simple-chat. Это ошеломляет.   -  person Shervin Asgari    schedule 01.10.2015
comment
Кажется, это связано с github.com/twbs/bootstrap/issues/16720, но не могу найти обходной путь   -  person Shervin Asgari    schedule 01.10.2015


Ответы (2)


Я объясню это в отношении бутстрапа.
Wiredep выбирает файлы из bower_components/{bootstrap}/bower.json > "основное" значение.
Файл бутстрапа css не указан в этом значении. Для теста/забавы отредактируйте вышеупомянутый файл, как показано ниже:

"moduleType": "globals",
"main": [
    "less/bootstrap.less",
    "dist/js/bootstrap.js",
    "dist/css/bootstrap.css"
  ],...

Обратите внимание на dist/css/bootstrap.css в значении main.
Теперь запустите grunt или grunt build. Вы обнаружите, что bootstrap/dist/css/bootstrap.css внедряется в app/index.html в место, которое вы ожидаете.

Это не ответ на вашу проблему, вы можете обратиться к ошибке в начальной загрузке https://github.com/twbs/bootstrap/issues/16663.

Однако моим последним предложением было бы перейти на bootstrap 3.3.1, пока они не решат проблему.

Извините, я не могу придумать лучшего решения, это «Их» решение.

Вы можете проверить это для всех библиотек, у которых возникли проблемы, либо поднять проблему в своем репо, либо перейти на более раннюю версию, либо подождать, пока она не станет стабильной.

person jsNovice    schedule 06.10.2015
comment
Спасибо. На данный момент я отредактировал файл bower.json вручную. Я мог бы понизить позже - person Shervin Asgari; 06.10.2015

Глядя на вашу проблему, у меня есть сильная интуиция, что ваш новый пакет Bower должен использовать другую версию общего зависимого пакета, например: ваш новый пакет мог загружать последнюю версию общего зависимого пакета, т.е. JQuery, и может также загружать его в время самой установки.

и когда при подключении зависимостей вы сталкиваетесь с этой проблемой.

Я не уверен, но это работает так.

person Sheelpriy    schedule 08.03.2018