gulp-livereload热更新

1. 新建一个项目文件夹。

npm init --yes
npm install express 
npm install --save-dev gulp gulp-liverload gulp-replace

2. 项目根目录下新建app.js

const path = require('path')
const express = require('express')
const app = new express();
const port = 3000;

app.use(express.static('public'));
app.get('/*', (req, res) => {
  res.sendFile(path.join(__dirname, 'views', 'index.html'));
})

app.listen(port, (error) => {
  if (error) {
    console.error(error);
  } else {
    console.info('==> Listening on port %s. Open up http://localhost:%s/ in your browser.', port, port);
  }
});

3. 项目根目录下新建 views/index.html

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>标题</title>
    <link rel="stylesheet" href="./css/index.css">
  </head>
  <body>
    <p class="red">测试2333</p>
  </body>
</html>

4.项目根目录下新建 public/css/index.css

.red{
  color: blue;
}

5.为package.json的scripts添加命令start

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node app.js"
  },

6.前面都是铺垫,重头戏来了。项目根目录下新建gulpfile.js

watch任务可以监测文件变动,达到热更新效果

dist任务打包文件

const gulp = require('gulp')
const livereload = require('gulp-livereload')
const exec = require('child_process').exec
const replace = require('gulp-replace')

gulp.task('watch',function(){
  livereload.listen();
  gulp.watch('views/*.html',function(file){
    livereload.changed(file.path)
  })
  gulp.watch('public/**/*.*',function(file){
      livereload.changed(file.path);
  });
})
gulp.task('start', function() {
  exec('npm start')
})
gulp.task('dist', function() {
  gulp.src('./views/*.html')
    .pipe(replace('src="js', 'src="./js'))
    .pipe(gulp.dest('./dist'))

  gulp.src('./public/js/*.js')
    .pipe(gulp.dest('./dist/js'))

  gulp.src('./public/css/*.css')
    .pipe(gulp.dest('./dist/css'))

  gulp.src('./public/img/*.+(jpeg|jpg|png|gif)')
    .pipe(gulp.dest('./dist/img'))

  gulp.src('./public/media/*.+(mp4|webm)')
    .pipe(gulp.dest('./dist/media'))
})
gulp.task('default', ['start', 'watch'])

7.做到这一步,就差最后一步,为chrome安装扩展程序liverload

下载链接:https://download.csdn.net/download/qq_30604453/10824629

下载解压后直接将LiveReload_v2.1.0.crx拖入chrome扩展程序面板即可。

 

所有铺垫都做完了。启动项目,开启git bash窗口,运行gulp

在浏览器中打开localhost:3000,并点击liverload使其中心圆圈变成实心。就实现了简易的热更新效果。在IDE中修改代码ctrl+s后,浏览器自动刷新代码。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值