node.js - Browsersync 不重新加载浏览器或注入(inject) css

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

几天来我一直在努力解决这个问题,但一直没能按照我需要的方式工作。我无法找到其他人使用 Browsersync 与 .net core 的任何示例,这甚至可能是我遇到所有这些问题的原因。但我找不到任何证据证明这一点,也不明白为什么会这样。

无论如何...我的 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 注入(inject)浏览器。

正如我所提到的,我以前使用过 gulp,并且此设置与我在进行 Wordpress 开发时使用的 gulp 文件非常接近。但是,它不适用于该项目(这导致我对 .net core/Visual Studio 产生怀疑)。

最佳答案

你可以做这样的事情

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

这段代码是我在 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

关于node.js - Browsersync 不重新加载浏览器或注入(inject) css,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53531151/

相关文章:

node.js - 使用 docker 的简单 Node.js 工作流程

asp.net - 在 Azure 上持续部署 ASP.NET 5 Beta 7

c# - 如何在 asp.net web api 中实现幂等 key ?

c# - 如何用修饰的实现覆盖作用域服务?

c# - IEnumerable 的早期执行

c# - 在单元测试中反序列化 appsettings.json

node.js - Express 服务器发送空 PDF 文件

ios - node-apn 库中出现奇怪的语法错误

node.js - Aws Cognito 联合身份在 getOpenIdTokenForDeveloperIdentity() 上回答 UnknownError Not Found

ssl - 将 Identityserver4 与 asp.net 核心 Web 服务器一起使用时有两个证书?