2

我正在尝试解决一个困扰我一段时间的问题。

场景:

问题是当我使用 Gulp 通过 Live Reload 启动本地服务器时。它可以很好地启动我的 Angular 应用程序,但是当我进行文件更改时,Live Reload(页面刷新)会破坏我的应用程序并给我一个“CANNOT GET”,因为我的 server.js(节点服务器)文件有一种特殊的重定向方式用户到我的“index.html”文件。原因是我在 Angular 应用程序中启用了“HTML5 模式”(对于漂亮的 URL),我必须在 server.js 文件中指定它才能正常工作。

在我在我的 Angular 应用程序中打开“html5 on”之前,一切正常,但由于特殊的重定向,我的 Gulp.js 文件没有正确写入以意识到这一点。

但是,如果我运行“node server.js”,角度应用程序会按预期工作并刷新页面,当我开发时遇到这个问题会很烦人。

问题:

  • 如何编写我的 gulpfile.js 以正确运行 server.js 文件?
  • 有没有更好的方法来编写我的 server.js 文件?
  • 是否可以一次运行多个端口(开发模式和生产模式)?


(我省略了一些文件夹和文件,以使其更容易看到)

文件结构:

  • 构建(角度生产应用程序)
  • 前端(角度开发应用程序)
  • gulpfile.js (任务运行器)
  • server.js (节点服务器)


Server.js(节点服务器)

var express = require('express');
var app = express();

app.use('/js', express.static(__dirname + '/front/js'));
app.use('/build', express.static(__dirname + '/../build'));
app.use('/css', express.static(__dirname + '/front/css'));
app.use('/images', express.static(__dirname + '/front/images'));
app.use('/pages', express.static(__dirname + '/front/pages'));

app.all('/*', function(req, res, next) {

    // Sends the index.html for other files to support HTML5Mode
    res.sendFile('/front/index.html', { root: __dirname });
});

var port = process.env.PORT || 8000;
app.listen(port);


Gulpfile(“连接”从第 67 行开始)

var gulp          = require ('gulp'),
    sync          = require ('browser-sync'),
    bower         = require ('gulp-bower'),
    htmlify       = require ('gulp-minify-html'),
    uglify        = require ('gulp-uglify'),
    prefix        = require ('gulp-autoprefixer'),
    minify        = require ('gulp-minify-css'),
    imgmin        = require ('gulp-imagemin'),
    rename        = require ('gulp-rename'),
    concat        = require ('gulp-concat'),
    inject        = require ('gulp-inject'),
    connect       = require ('gulp-connect'),
    open          = require ('gulp-open');

// Bower Task
gulp.task('bower', function() {
    return bower()
      .pipe(gulp.dest('front/js/vendors'));
});

// HTML Task
gulp.task('html', function(){
    gulp.src('front/**/*.html')
      .on('error', console.error.bind(console))
      .pipe(gulp.dest('build'))
      .pipe(connect.reload());
});

// Styles Task (Uglifies)
gulp.task('styles', function(){
    gulp.src('front/**/*.css')
      .pipe(minify())
      .on('error', console.error.bind(console))
      .pipe(gulp.dest('build'))
      .pipe(connect.reload());
});

// Scripts Task (Uglifies)
gulp.task('scripts', function(){
    gulp.src('front/**/*.js')
      .pipe(uglify())
      .on('error', console.error.bind(console))
      .pipe(gulp.dest('build'))
      .pipe(connect.reload());
});

// Image Task (compress)
gulp.task('images', function(){
    gulp.src('front/images/*')
      .pipe(imgmin())
      .pipe(gulp.dest('build/images'))
      .pipe(connect.reload());
});

// Connect Task (connect to server and live reload)
gulp.task('connect', function(){
    connect.server({
      root: 'front',
      livereload: true
    });
});

// Watch Task (watches for changes)
gulp.task('watch', function(){
    gulp.watch('front/*.html', ['html']);
    gulp.watch('front/js/*.js', ['scripts']);
    gulp.watch('front/css/*.css', ['styles']);
    gulp.watch('front/images/*', ['images']);
});

// Open Task (starts app automatically)
gulp.task("open", function(){
  var options = {
    url: "http://localhost:8080",
    app: "Chrome"
  };
  gulp.src("front/index.html")
  .pipe(open("", options));
});

gulp.task('default', ['html', 'styles', 'scripts', 'images', 'connect', 'watch', 'open']);



角应用

// App Starts
angular
    .module('app', [
        'ui.router',
        'ngAnimate',
        'angular-carousel'
    ])
    .config(['$urlRouterProvider', '$stateProvider', '$locationProvider', function($urlRouterProvider, $stateProvider, $locationProvider) {
        $urlRouterProvider.otherwise("/");

        $stateProvider
            // Home Page
            .state('home', {
                url: '/',
                templateUrl: 'pages/home.html',
                controller: 'homeCtrl'
            })

        // use the HTML5 History API
        $locationProvider.html5Mode(true);
    }])



索引.html

    <!DOCTYPE html>
    <html class="no-js" ng-app="app" ng-controller="mainCtrl">
    <head>
        <title>Website</title>
        <meta charset="utf-8"/>

        <!-- Universal Stylesheets -->
        <link href="css/stylesheet.css" type="text/css" rel="stylesheet" />
        <!-- Sets base for HTML5 mode -->
        <base href="/"></base>
    </head>

    <body>
      <section class="row main" ui-view></section>

        <!-- Javascript -->
        <script src="js/scripts.js"></script>
    </body>

    </html>

在此先感谢您的帮助!

4

1 回答 1

1

这是一个相当不错的解决方案:)

这是您应该使用的:

gulp.task('connect', connect.server({
  root: ['build'],
  port: 9000,
  livereload: true,
  open: {
    browser: 'Google Chrome'
  },
   middleware: function(connect, opt) {
      return [ historyApiFallback ];
    }
}));

这是我用于 SPA 开发的模块:

"connect-history-api-fallback": "0.0.5",

AngularJs 也有一个巧妙的解决方案来避免设置基本 href

$locationProvider.html5Mode({enabled: true, requireBase: false})
于 2014-11-02T01:45:55.553 回答