Browsersync不会重新加载浏览器或注入CSS

问题描述 投票:1回答:1

我已经尝试了好几天了,但是一直无法按照我需要的方式工作。我找不到其他使用带有.net core的Browsersync的人的例子,这甚至可能就是我遇到所有这些问题的原因。但是我找不到任何证据可以证明这一点,也无法理解为什么会如此。

无论如何...我已经在gulp文件中正常运行了sass / js所需的所有内容,以处理错误等。我对gulp并不陌生,否则我会因为缺乏经验而怪无法使此工作。

这是我的gulp文件,后面是运行gulp时的输出。

默认任务:

const   gulp = require("gulp"),
        uglify = require("gulp-uglify"),
        sass = require("gulp-sass"),
        rename = require('gulp-rename'),
        sassGlob = require('gulp-sass-glob'),
        postcss = require('gulp-postcss'),
        autoprefixer = require('gulp-autoprefixer'),
        sourcemaps = require('gulp-sourcemaps'),
        cleanCSS = require('gulp-clean-css'),
        concat = require('gulp-concat'),
        msbuild = require('gulp-msbuild'),
        through = require('through2'),
        notifier = require('node-notifier'),
        browserSync = require('browser-sync').create();

// Static Server + watching scss/html files
gulp.task('serve', ['sass', 'compileJS'], function() {

    browserSync.init({
        proxy : {
            target: "https://localhost:3000",
        },
        files: ['./wwwroot/css/*'],

        rewriteRules: [
            {
                match: new RegExp('/css/main.min.css'),
                fn: function() {
                    return './wwwroot/css/main.min.css'
                }
            }
        ]
    });


    //Watch for any changes to the scss files.
    gulp.watch('./wwwroot/sass/**/*.scss', ['sass']);

    //Watch for any changes to the js files, reload after those changes are made.
    gulp.watch('./wwwroot/js/source/*.js', ['compileJS']).on('change', browserSync.reload);

    //Watch for any changes to a .cshtml file and reload the browser if/when that change happens.
    gulp.watch("./**/*.cshtml").on('change', browserSync.reload);
});

gulp.task('default', ['serve']);


/**
 * Compiles SASS files and stores the result into the public folder
 */
gulp.task('sass', function () {

    return gulp.src('./wwwroot/sass/main.scss')
        .pipe(sassGlob())
        .pipe(sass().on('error', function (err) {
            console.log('Sass Error:', err.toString());

            notifier.notify({
                'title': 'Gettin\' Sassy 💁‍♀️',
                'message': 'You goofed. Check your terminal window for more information.'
            });

            this.emit("end");
        }))
        .pipe(postcss([require('autoprefixer')]))
        .pipe(
            autoprefixer({
                browsers: ['last 2 versions'],
                cascade: false
            })
        )
        .pipe(
            through.obj(function(chunk, enc, cb) {
                cb(null, chunk)
            })
        )
        .pipe(cleanCSS({compatibility: 'ie8',
            level: 2}))
        .pipe(rename({suffix: '.min'}))
        .pipe(gulp.dest('./wwwroot/css'))
        .pipe(browserSync.stream());
});

/**
 * Compiles the Javascript files and stores the result in the public folder
 */
gulp.task('compileJS', function (done) {

    return gulp.src('./wwwroot/js/source/*.js')
        .pipe(sourcemaps.init())
        .pipe(concat('main.js'))
        .pipe(uglify().on('error', function (err) {
            console.log('JS Uglify Error:', err.toString());

            notifier.notify({
                'title': 'JS Compile Error',
                'message': 'Something about your JS is a little off. Check yourself before you wreck yourself.'
            });

            this.emit("end");
        }))
        .pipe(rename({suffix: '.min'}))
        .pipe(sourcemaps.write('../maps'))
        .pipe(gulp.dest('./wwwroot/js/dist'));
});

输出:

$ gulp
[21:34:15] Using gulpfile 
~/Repos/PROJECT_DIRECTORY/PROJECT_NAME/gulpfile.js
[21:34:15] Starting 'sass'...
[21:34:15] Starting 'compileJS'...
[21:34:15] Finished 'sass' after 437 ms
[21:34:15] Finished 'compileJS' after 426 ms
[21:34:15] Starting 'serve'...
[21:34:16] Finished 'serve' after 1 s
[21:34:16] Starting 'default'...
[21:34:16] Finished 'default' after 68 μs
[Browsersync] Proxying: https://localhost:3000
[Browsersync] Access URLs:
 ------------------------------------
        Local: https://localhost:3000
     External: https://10.0.0.137:3000
 ------------------------------------
          UI: http://localhost:3001
 UI External: http://localhost:3001
 ------------------------------------
[21:34:35] Starting 'sass'...
[Browsersync] 1 file changed (main.min.css)
[21:34:35] Finished 'sass' after 207 ms
[21:34:58] Starting 'compileJS'...
[21:34:58] Finished 'compileJS' after 154 ms
[Browsersync] Reloading Browsers...

因此,查看该输出,您可能会想自己:“这个家伙是个白痴……Browsersync声明正在重新加载浏览器...”正确,它声明了这一点,但并未重新加载浏览器。 Browsersync也同样无法将我的CSS注入浏览器。

正如我提到的,我以前使用过gulp,并且此设置也非常代表我在进行Wordpress开发时使用的gulp文件。但是,它不适用于该项目(这使我陷入了.net核心/ Visual Studio的怀疑)。

node.js asp.net-core .net-core gulp browser-sync
1个回答
0
投票

您可以做这样的事情

创建对您的应用程序全局的环境变量,然后在视图中的结束标记上方,可以添加以下代码。

此代码是我在我的Blade模板中使用Laravel进行的操作,但是应该完全相同,只需要用.NET来替换它,我认为它们使用Razor模板引擎:)

  {{-- Live reload with browser sync --}}

  @if (!empty(env('APP_ENV')) && env('APP_ENV') === 'local') 
    <script 
      async 
      defer 
      src="{{ URL::to('/') . ':3000/browser-sync/browser-sync-client.js?v=2.26.7'}}">
    </script>
  @endif

希望这对您有所帮助。

为方便起见,下面是我的大口水管道:

const browserSync = require("browser-sync");
const sass = require("gulp-sass");
const autoprefixer = require("gulp-autoprefixer");
const sourcemaps = require("gulp-sourcemaps");
const rename = require("gulp-rename");
const reviser = require("gulp-rev");
const runSequence = require("run-sequence");

gulp.task("browserSync", function() {
  return browserSync.init({
    open: false,
    https: false,
    notify: false,
    injectChanges: true,
    proxy: "http://{site-name-here}.local/",
    target: "http://{site-name-here}.local/"
  });
});

gulp.task("compile:scss", function() {
  return (
    gulp
      // Gets the main.scss file
      .src("resources/assets/scss/main.scss")
      // Passes it through a gulp-sass, log errors to console
      .pipe(sass().on("error", sass.logError))
      // Adds versioning
      .pipe(reviser())
      // Add vendor prefixes
      .pipe(
        autoprefixer({
          browsers: ["last 2 versions"],
          cascade: false
        })
      )
      // Rename the file
      .pipe(rename({ suffix: ".min" }))
      // Outputs it in the css folder
      .pipe(gulp.dest("public/css"))
      // Add sourcemaps
      .pipe(sourcemaps.write())
      // Adds versioned file to manifest so we can access with the same name
      .pipe(reviser.manifest("manifest/rev-manifest.json"), { merge: true })
      // Outputs it in the css folder
      .pipe(gulp.dest("public/css")) 
      .pipe(
        browserSync.reload({
          // Reloading with Browser Sync
          stream: true
        })
      )
  );
});

// Watchers
gulp.task("watch", function() {
  gulp.watch(["./resources/assets/scss/**/*"], "compile:scss", browserSync.reload);
});

// Default task
gulp.task("start", function(callback) {
  return runSequence(
    "browserSync",
    "compile:scss",
    "watch",
    callback
  );
});

要使用它,我只需运行gulp start

请注意,像这样运行gulp,您需要在全局范围内安装gulp。为此运行npm install --global gulp-cli

© www.soinside.com 2019 - 2024. All rights reserved.