【问题标题】:Browsersync not reloading browser or injecting cssBrowsersync 不重新加载浏览器或注入 css
【发布时间】:2018-11-29 02:52:23
【问题描述】:

几天来,我一直在努力解决这个问题,但无法让它按照我需要的方式工作。我找不到其他人使用带有 .net 核心的 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 core / Visual Studio 产生了怀疑)。

【问题讨论】:

    标签: node.js asp.net-core .net-core gulp browser-sync


    【解决方案1】:

    你可以这样做

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

    这段代码是我在 Laravel 中使用 Blade 模板的方式,但它应该完全相同,您只需将其替换为 .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
    

    希望这对您有所帮助。

    出于兴趣,下面是我的 gulp 管道:

    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/",
      });
    });
    
    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-04
      • 2018-05-24
      • 2017-08-29
      • 2017-10-01
      • 2015-09-29
      相关资源
      最近更新 更多