gulp 启动后没有报错,但在浏览器里一直打不开

发布于 2022-09-07 08:40:24 字数 8603 浏览 13 评论 0

npm start 运行结果

$ npm start

> voteapp@1.0.0 start E:\project\PumpkinCage\Pumpkin\server
> set NODE_ENV=development&& gulp default

[15:53:55] Using gulpfile E:\project\PumpkinCage\Pumpkin\server\gulpfile.js
[15:53:55] Starting 'default'...
[15:53:55] Starting 'build'...
[15:53:55] Starting 'clean'...
[15:53:55] Finished 'clean' after 30 ms
[15:53:55] Starting 'fonts'...
[15:53:55] Starting 'copy'...
[15:53:55] Starting 'less'...
[15:53:55] Starting 'js'...
[15:53:55] Starting 'img'...
[15:53:55] gulp-fontmin: Minified 1 font
[15:53:55] Finished 'less' after 409 ms
[15:53:55] Finished 'copy' after 411 ms
[15:53:55] Finished 'img' after 414 ms
[15:53:55] Finished 'fonts' after 429 ms
[15:53:55] Finished 'js' after 422 ms
[15:53:55] Starting 'html'...
[15:53:55] Finished 'html' after 47 ms
[15:53:55] Finished 'build' after 512 ms
[15:53:55] Starting 'nodemon'...
[15:53:55] [nodemon] 1.11.0
[15:53:55] [nodemon] to restart at any time, enter `rs`
[15:53:55] [nodemon] watching: *.*
[15:53:55] [nodemon] starting `node app`
[15:53:55] Finished 'nodemon' after 98 ms
[15:53:55] Starting 'browser-sync'...
[15:53:56] Finished 'browser-sync' after 26 ms
[15:53:56] Starting 'watch'...
监听端口:3000
环境:development
[BS] Proxying: http://localhost:3000
[BS] Access URLs:
 --------------------------------------
       Local: http://localhost:7000
    External: http://192.168.1.176:7000
 --------------------------------------
          UI: http://localhost:3001
 UI External: http://192.168.1.176:3001
 --------------------------------------
[BS] Watching files...

package.json 部分代码

"scripts": {
    "start": "set NODE_ENV=development&& gulp default",
    "pro": "set NODE_ENV=production& npm run build& node app",
    "restart": "forever restart bin/www",
    "stop": "forever stop bin/www",
    "build": "gulp build",
    "test": "node bin/www"
}

gulpfile.js 文件

'use strict';
var path = require('path');
var del = require('del');
var browserSync = require('browser-sync');
var runSequence = require('run-sequence');
var gulp = require('gulp');
var gulpif = require('gulp-if');
var minify = require('gulp-clean-css');
var nodemon = require('gulp-nodemon');
var cache = require('gulp-cache');
var uglify = require('gulp-uglify');
var htmlmin = require('gulp-htmlmin');
var fontmin = require('gulp-fontmin');
var less = require('gulp-less');
var concat = require('gulp-concat');
var jshint = require('gulp-jshint');
var cssBase64 = require('gulp-base64');
var autoprefixer = require('gulp-autoprefixer');
var rev = require('gulp-rev-ayou');
var revCollector = require('gulp-rev-collector-ayou');

var reload = browserSync.reload;

var NODE_ENV = process.env.NODE_ENV;

var staticPath = 'dist/static/';

// 读取所有的中文
// var zh_CN = require('./lang/zh_CN');
// var text = (function() {
//   var _text = '';
//   function TraversalObject(obj) {
//     for (var a in obj) {
//       if (typeof (obj[a]) == "object") {
//         TraversalObject(obj[a]); //递归遍历
//       }
//       else {
//         _text += obj[a];
//       }
//     }
//   }
//   TraversalObject(zh_CN);
//   return _text + 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890.,;:\'(!?)+-*/=';
// })()

var text = 'fdg'

// 删除文件
gulp.task('clean', function(cb) {
  return del(['dist/static/', 'dist/views/']);
});

// 拷贝lib文件
gulp.task('copy', function(cb) {
  return gulp.src('./public/lib/**/*')
    .pipe(gulp.dest(staticPath + 'lib'))
});

// 转换并精简fonts文件
gulp.task('fonts', function() {
  return gulp.src('./public/fonts/**/*')
    .pipe(fontmin({
      text: text
    }))
    .pipe(gulp.dest(staticPath + 'fonts'))
});

// html
gulp.task('html', function() {
  return gulp.src(['dist/rev/**/*.json', 'views/**/*.html'])
    .pipe(revCollector())
    .pipe(htmlmin({collapseWhitespace: true, minifyCSS: true, minifyJS: true}))
    .pipe(gulp.dest('dist/views/'))
});

// less
gulp.task('less', function () {
  return gulp.src('public/less/**/*.less')
    .pipe(less({
        paths: [ path.join(__dirname, 'less', 'includes') ]
    }))
    .pipe(cssBase64())
    .pipe(autoprefixer({
      browsers: ['last 2 versions', 'Android >= 4.0', 'last 3 Safari versions'],
      cascade: true, //是否美化属性值 默认:true 像这样:
      //-webkit-transform: rotate(45deg);
      //        transform: rotate(45deg);
      remove:true //是否去掉不必要的前缀 默认:true
    }))
    .pipe(minify())
    .pipe(rev())
    .pipe(gulp.dest(staticPath + 'css'))
    .pipe(rev.manifest())
    .pipe(gulp.dest('dist/rev/css'))
});

// js
gulp.task('js', function () {
    return gulp.src('public/js/**/*.js')
      // .pipe(jshint({

      // }))
      // .pipe(jshint.reporter('default'))
      .pipe(gulpif(
        NODE_ENV === 'production' || NODE_ENV === 'test',
        uglify({ compress: true }))
      )
      .pipe(rev())
      .pipe(gulp.dest(staticPath + 'js'))
      .pipe(rev.manifest())
      .pipe(gulp.dest('dist/rev/js'))
});

// img
gulp.task('img', function() {
  return gulp.src(['public/img/**/*','public/img/*'])        //引入所有需处理的Img
    .pipe(gulp.dest(staticPath +  'img'));
});

// 浏览器同步,用7000端口去代理Express的3000端口
gulp.task('browser-sync', function() {
  var files = ["views/**/*.*","css/*.*","css/**/*.*","js/*.*","img/*.*"].map((a) => {
    return staticPath + a;
  })
  browserSync.init(null, {
    proxy: "http://localhost:3000",
    files: files,
    port: 7000
  });
});

// 开启Express服务
gulp.task('nodemon', function (cb) {

  var started = false;

  return nodemon({
    script: 'app'
  }).on('start', function () {
    // to avoid nodemon being started multiple times
    // thanks @matthisk
    if (!started) {
      cb();
      started = true;
    }
  });
});

gulp.task('build', function (cb) {
    runSequence('clean', ['fonts', 'copy', 'less', 'js', 'img'], 'html', cb);
});

gulp.task('less-watch', ['less'], reload);
gulp.task('js-watch', ['js'], reload);
gulp.task('img-watch', ['img'], reload);
gulp.task('html-watch', ['html'], reload);

gulp.task('watch', function (cb) {
  // 监听所有css文档
  gulp.watch('public/less/**/*.less', ['less-watch']);

  // 监听所有.js档
  gulp.watch('public/js/**/*.js', ['js-watch']);

  // 监听lib
  // gulp.watch('public/lib/jquery-plugins/*.js', ['copy-watch']);

  // 监听所有图片档
  gulp.watch('public/img/**/*', ['img-watch']);

  // 监听ejs
  gulp.watch('views/**/*.html', ['html-watch']);
});

gulp.task('default', function(cb) {
  runSequence('build', 'nodemon', ['browser-sync', 'watch']);
});

app.js

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var swig = require('swig');
var env = require('./env').env;
var log4js = require('log4js');
var utils = require('./utils/utils');

var port = env.port;
var app = express();

var NODE_ENV = process.env.NODE_ENV || 'development';

global.token = null;

// view engine setup
// Disables caching in Swig.
swig.setDefaults({ cache: false });
app.engine('html', swig.renderFile);
app.set('views', path.join(__dirname, 'dist/views'));
app.set('view engine', 'html');

// uncomment after placing your favicon in /public
app.use(favicon(path.join(__dirname, 'favicon.ico')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
let _maxAge = NODE_ENV === 'production' ? 30*24*3600*1000 : -1;
app.use(express.static(path.join(__dirname, 'dist/static'), {maxAge: _maxAge}));

// 日志
var appLog = log4js.getLogger('app'), // 程序日志
  httpLog = log4js.getLogger('http'); // 访问日志
global.appLog = appLog; // 挂载到全局
utils.mkdirsSync('../logs/node');
utils.mkdirsSync('../logs/c2node');
utils.mkdirsSync('../logs/node2s');
log4js.configure('./log4js.json');
app.use(log4js.connectLogger(httpLog, { level: 'auto' }));

utils.autoLogin()
// 路由配置
require('./routes/index')(app);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// 404
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// api错误处理
app.use('/api', function (err, req, res, next) {
  global.appLog.error('Api error :' + err && err.stack || err);
  res.json(err);
});

// 启动服务
app.listen(port, err => {
  console.log(err || '监听端口:' + port);
  console.log('环境:' + NODE_ENV);
});

浏览器: 3000端口也是一样的
图片描述

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

请持续率性 2022-09-14 08:40:24
browserSync.init({
                server:{
                    baseDir:paths.source.root
                },
                open:"external"  //自己浏览器的IP
            });
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文