gulp打包css,js檔案
阿新 • • 發佈:2022-05-22
gulp學習記錄
npm init -y
yarn add gulp -D
修改 package.json
"scripts": {
"build": "gulp"
},
// 檢視版本
npx gulp --version
新建 gulpfile.js
// 重新命名
gulp-rename
// 壓縮js
gulp-uglify
yarn add [email protected] [email protected]
[email protected]
[email protected]
[email protected]
-D
npm run build
yarn add browser-sync -D
------------------
gulpfile.js
const {src,dest,series,watch} = require('gulp') const browserSync = require('browser-sync').create() const reload = browserSync.reload const del = require('del') 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() }
// 對 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.styles = css exports.clean = clean exports.default = series([ clean, js, css, serve, watcher ]) ---------package.json----------- { "name": "gulp", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "build": "gulp" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "browser-sync": "^2.27.10", "del": "^6.1.0", "gulp": "^4.0.2", "gulp-autoprefixer": "^8.0.0", "gulp-load-plugins": "^2.0.7", "gulp-sass": "4.0.2", "gulp-uglify": "^3.0.2" }, "browserslist": [ "last 2 Version", "> 2%" ] } ---------------index.html------------------- <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="./dist/css/index.css"> </head> <body> hello Eric
<script src="./dist/js/index.js"></script> </body> </html> -------------------------