使用nodejs提供的api
const fs = require('fs')
const { Transform } = require('stream')
exports.default = () => {
//文件读取流
const readStream = fs.createReadStream('app.css')
//文件写入流
const writeStream = fs.createWriteStream('app.min.css')
//文件转换流
const transFrom = new Transform({
transform: (chunk, encoding, callback) => {
//转换过程
//chunk :读取流中取到的内容(Buffer)
const input = chunk.toString()
const output = input.replace(/\/\*(.|\n)*?\*\//g, "") //删除注释
.replace(/\s*([\{\}\:\;\,])\s*/g, "$1")
.replace(/\,[\s\.\#\d]*\{/g, "{")//容错处理
.replace(/;\s*;/g, ";")//清除连续分号
callback(null, output)
}
})
readStream.pipe(transFrom).pipe(writeStream)
return readStream
}
使用Gulp 提供的插件 gulp-clean-css, gulp-rename
const { src, dest } = require('gulp')
const cleanCss = require('gulp-clean-css')
const rename = require('gulp-rename')
exports.default = () => {
return src('app.css')
.pipe(cleanCss())
.pipe(rename({ extname: '.min.css' }))
.pipe(dest('.'))
}