Синхронизация браузера не может перезагрузить страницу после обработки файлов SASS - PullRequest
0 голосов
/ 06 сентября 2018

Я новичок в Drupal 8 и у меня возникли проблемы с настройкой среды. У меня есть gulpfile.js, который должен создать файл style.css из файлов SASS, очистить все кэши и обновить мой браузер, используя browser-sync . Моя проблема заключается в том, что при синхронизации браузера не удается обновить страницу при создании нового файла CSS из файлов SASS.

gulpfile.js

var gulp = require('gulp');
var sass = require('gulp-sass');
var autoprefixer = require('gulp-autoprefixer');
var sourcemaps = require('gulp-sourcemaps');
var notify = require('gulp-notify');
var shell = require('gulp-shell');
var browserSync = require('browser-sync').create();

// Error notifications
var reportError = function(error) {
  notify({
    title: 'Gulp Task Error',
    message: 'Check the console.'
  }).write(error);
  console.log(error.toString());
  this.emit('end');
}
var config = {
    bootstrapDir: './bootstrap',
};

// Sass processing
gulp.task('sass', function() {
  return gulp.src('scss/**/*.scss')
    .pipe(sourcemaps.init())
    // Convert sass into css
    .pipe(sass())
    // Show errors
    .on('error', reportError)
    // Autoprefix properties
    .pipe(autoprefixer({
      browsers: ['last 2 versions']
    }))
    // Write sourcemaps
    .pipe(sourcemaps.write())
    // Save css
    .pipe(gulp.dest('css'))
    .pipe(notify({
      title: "SASS Compiled",
      message: "Your CSS files are ready.",
      onLast: true
    }));
});

// Run drush to clear the caches
gulp.task('drush', function() {
  return gulp.src('.', {
      read: false
    })
    .pipe(shell([
      'drush cr',
    ]))
    .pipe(notify({
      title: "Caches cleared",
      message: "Drupal caches cleared.",
      onLast: true
    }));
});

// BrowserSync reload
gulp.task('reload', function(done){
     gulp.src('css')
     .pipe(browserSync.reload({stream: true}))
     .pipe(notify({
       title: "Reload",
       message: "Browser reloaded.",
       onLast: true
     }));
     done();
});

// BrowserSync init
gulp.task('browser-sync', function(done){
  browserSync.init({
     injectChanges: true,
     server: {
      baseDir: './'
     }
  });

  gulp.watch('scss/**/*.scss', gulp.series('sass'));
  gulp.watch('css/style.css').on('change', gulp.series('drush','reload'));
});

// Default task to be run with `gulp`
gulp.task('default', gulp.series('sass','drush','browser-sync'));

выход

Вот вывод консоли после изменения одного из файлов SASS.

$ gulp
[19:08:27] Using gulpfile ~/Documents/Web/d8/themes/custom_theme/gulpfile.js
[19:08:27] Starting 'default'...
[19:08:27] Starting 'sass'...
[19:08:27] gulp-notify: [SASS Compiled] Your CSS files are ready.
[19:08:27] Finished 'sass' after 617 ms
[19:08:27] Starting 'drush'...
 [success] Cache rebuild complete.
[19:08:29] gulp-notify: [Caches cleared] Drupal caches cleared.
[19:08:29] Finished 'drush' after 1.48 s
[19:08:29] Starting 'browser-sync'...
[Browsersync] Access URLs:
 --------------------------------------
       Local: http://localhost:3000
    External: http://192.168.1.103:3000
 --------------------------------------
          UI: http://localhost:3001
 UI External: http://192.168.1.103:3001
 --------------------------------------
[Browsersync] Serving files from: ./
[19:08:38] Starting 'sass'...
[19:08:38] gulp-notify: [SASS Compiled] Your CSS files are ready.
[19:08:38] Finished 'sass' after 519 ms
[19:08:38] Starting 'drush'...
 [success] Cache rebuild complete.
[19:08:40] gulp-notify: [Caches cleared] Drupal caches cleared.
[19:08:40] Finished 'drush' after 1.43 s
[19:08:40] Starting 'reload'...
[19:08:40] Finished 'reload' after 1.97 ms
[Browsersync] 1 file changed (css)
[19:08:40] gulp-notify: [Reload] Browser reloaded.
[Browsersync] Reloading Browsers...

Мы видим, что файл CSS создан, кэши очищены и перезагрузка запускается, как и ожидалось, но изменения не применяются к странице браузера ...

package.json

Вот мои зависимости NPM.

{
  "name": "custom_theme",
  "version": "1.0.0",
  "description": "",
  "main": "gulpfile.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "browser-sync": "^2.24.7",
    "gulp": "^4.0.0",
    "gulp-autoprefixer": "^6.0.0",
    "gulp-notify": "^3.2.0",
    "gulp-sass": "^4.0.1",
    "gulp-shell": "^0.6.5",
    "gulp-sourcemaps": "^2.6.4"
  },
  "dependencies": {}
}

Модуль Drupal 8

Я также установил модуль Drupal 8 Browsersync , чтобы включить необходимый фрагмент JavaScript в тег HTML <body> из-за этого ответа.

Я что-то упустил?

1 Ответ

0 голосов
/ 08 сентября 2018

Итак, после нескольких часов борьбы я не смог выполнить эту работу, поэтому я переключился с browser-sync на gulp-livereload (требуется расширение для браузера).

gulpfile.js

var gulp = require('gulp');
var sass = require('gulp-sass');
var autoprefixer = require('gulp-autoprefixer');
var sourcemaps = require('gulp-sourcemaps');
var notify = require('gulp-notify');
var shell = require('gulp-shell');
var livereload = require('gulp-livereload');

// Error notifications
var reportError = function(error) {
  notify({
    title: 'Gulp Task Error',
    message: 'Check the console.'
  }).write(error);
  console.log(error.toString());
  this.emit('end');
}
var config = {
    bootstrapDir: './bootstrap',
};

// Sass processing
gulp.task('sass', function() {
  return gulp.src('scss/**/*.scss')
    .pipe(sourcemaps.init())
    // Convert sass into css
    .pipe(sass())
    // Show errors
    .on('error', reportError)
    // Autoprefix properties
    .pipe(autoprefixer({
      browsers: ['last 2 versions']
    }))
    // Write sourcemaps
    .pipe(sourcemaps.write())
    // Save css
    .pipe(gulp.dest('css'))
    .pipe(notify({
      title: "SASS Compiled",
      message: "Your CSS files are ready.",
      onLast: true
    }));
});

// Run drush to clear the caches
gulp.task('drush', function() {
  return gulp.src('css', {
      read: false
    })
    .pipe(shell([
      'drush cr',
    ]))
    .pipe(livereload())
    .pipe(notify({
      title: "Caches cleared + Reload",
      message: "Drupal caches cleared + browser reloaded.",
      onLast: true
    }));
});

// Watch modifications on defined files
gulp.task('watch', function() {
  livereload.listen();
  gulp.watch('./scss/**/*.scss', gulp.series('sass'));
  gulp.watch('./css/style.css', gulp.series('drush'));
  gulp.watch('./templates/**/*.twig', gulp.series('drush'));
});

// Default task to be run with `gulp`
gulp.task('default', gulp.series('sass','drush','watch'));

Теперь все отлично работает.

...