使用带有BrowserSync的连接中间件

时间:2016-09-16 10:32:44

标签: node.js yeoman middleware browser-sync

我尝试使用带有browserSync的gulp-connect中间件,但到目前为止我没有运气。

这是how it should be used

    ...
    middleware: function(){
        return [gulpConnectSsi({
            baseDir: __dirname + '/app',
            ext: '.html',
            domain: 'http://example.com/',
            method: 'readOnLineIfNotExist'  // readOnLine|readLocal|readOnLineIfNotExist|downloadIfNotExist
        })];
    }
    ...

我试图将其添加到gulp任务(yeoman webapp)

browserSync({
notify: false,
port: 9000,
logLevel: "debug",
server: {
  baseDir: ['.tmp', 'app'],   
  middleware: function(){
      return [gulpConnectSsi({
          baseDir: __dirname + '/app',
          ext: '.html',
          domain: 'http://localhost:9000/',
          method: 'readOnLineIfNotExist' 
      })];

  },
  routes: {
    '/bower_components': 'bower_components'
  }  
}
});

服务器启动但没有错误但没有提供任何服务。我试图找出browserSync official doc,但即使是最简单的例子也会挂起服务器。

// Multiple Global Middlewares
middleware: [
    function (req, res, next) {
        /** First middleware handler **/
    },
    function (req, res, next) {
        /** Second middleware handler **/
    }
]

使用带有browserSync的中间件的正确方法是什么?我错过了什么? browserSync中间件是否是常规的'那些来自Express或Gulp-connect的那些?

1 个答案:

答案 0 :(得分:0)

在我的配置中的browserSync和Webpack中间件配置下面:

/**
 * Browser Sync & webpack middleware
 */

var gulp                 = require ('gulp');
var browserSync          = require('browser-sync');
var webpackConfig        = require('./helpers/webpackConfig')();
var webpack              = require('webpack');
var compiler             = webpack(webpackConfig);
var webpackDevMiddleware = require('webpack-dev-middleware');
var webpackHotMiddleware = require('webpack-hot-middleware');
var path                 = require('path');

var mode                 = require('./helpers/mode');
var config               = require("../config");

var serverConfig = {
    logPrefix: "webman.pro",
    port: 3000,
    ui: {
        port: 3001
    }
};


// Run middleware only on development mode
if(!mode.production)
serverConfig.middleware = [
    webpackDevMiddleware(compiler, {
        noInfo: true,
        publicPath: path.join('/', webpackConfig.output.publicPath),
        stats: 'errors-only'
    }),
    webpackHotMiddleware(compiler)
]

// Change config when we have Server
config.proxy 
? serverConfig.proxy = config.proxy
: Object.assign(serverConfig, {
    server: {
        baseDir: config.root.dist,
    },
    tunnel: false,
})

var live = function(){
    browserSync.init(serverConfig);
};

gulp.task('live', live);