Glup

Gulp

前端构建工具,类似webpack。

  1. 方便使用
  2. 构建快速
  3. 插件系统
  4. 易于学习
gulp flow

扩展插件可以在npmjs上搜索到

安装

npm init -y 初始化项目
yarn add gulp -D 

Package.json

...
"scripts": {
    "build": "gulp"
  },  ..
 npx gulp --version 查看gulp版本
 npm run build 执行gulp

新建gulpfile.js文件

//压缩js
function js() {
  console.log("This is js scripts task")
}
//对scss/less 编译输出css文件
function css() {
    console.log("This is css styles task")

}
//监听这些文件的变化
function watcher() {

}
//删除dist目录中的内容
function clear() {

}
exports.scripts = js
exports.css = css
exports.default = function () {
    console.log("hello gulp")
}
查看gulp的task:
npx gulp --tasks 
执行单个task
npx gulp scripts

使用插件

插件列表

  1. Unglify 混淆 https://www.npmjs.com/package/gulp-uglify
  2. Rename 重命名 https://www.npmjs.com/package/gulp-rename
  3. Del 清空disk目录的https://www.npmjs.com/package/del
  4. Autoprefixer 样式预处理 https://www.npmjs.com/package/gulp-autoprefixer
  5. Sass 使用sass https://www.npmjs.com/package/gulp-sass
  6. loadplugins 方便引用插件,不用在插件名字前面加gulp-了 https://www.npmjs.com/package/gulp-load-plugins
yarn add gulp-sass gulp-autoprefixer gulp-load-plugins gulp-uglify del -D

实时编译

Browsersync+Gulp

https://www.browsersync.io/docs/gulp

yarn add browser-sync -D

Gulp file

const { src, dest, series, watch } = require('gulp')
const browserSync = require('browser-sync').create()
const reload = browserSync.reload
const del = require('del') //不是gulp开头,所以不能直接引用
//gulp-uginlify => plugins.uglify =require('gulp-uglify')
const plugins = require ('gulp-load-plugins')()

//压缩js
function js(cb) {
    src('js/*.js')
        .pipe(plugins.uglify())
        .pipe(dest('./dist/js'))
        .pipe(reload({ stream: true }))
    cb() //callback方法,异步任务gulp会报错,所以用一个callback来回调,就不会报错来
}
//对scss/less 编译输出css文件
function css(cb) {
    src('css/*.scss')
        .pipe(plugins.sass({ outputStyle: 'compressed'}))
        .pipe(plugins.autoprefixer({
            cascade: false,
            remove: false
        }))
        .pipe(dest('./dist/css'))
        .pipe(reload({ stream: true }))
    cb()
}
//监听这些文件的变化
function watcher() {

    watch('js/*.js',js)
    watch('css/*.scss',css)
}
//删除dist目录中的内容
function clean(cb) {
    del('./dist')
    cb()
}
//Server 任务
function serve(cb){
    browserSync.init({
        server: {
             baseDir: './'
        }
    })
    cb()
}

exports.scripts = js
exports.css = css
exports.clean = clean
exports.watche = watcher
exports.default = series ([
    clean,
    js,
    css,
    serve,
    watcher
])

你可能感兴趣的:(Glup)