首页 > 代码库 > 基于gulp 的前端自动化构建方案总结

基于gulp 的前端自动化构建方案总结

先安装nodejs

 使用淘宝镜像安装tnpm

  1. 安装 cnpm 插件:npm install -g cnpm --registry=https://registry.npm.taobao.org

    然后就可以用 cnpm命令从淘宝镜像获取插件包了;当然,你这时候依旧可以用npm命令从官方服务获取插件包。

cnpm支持除 publish 之外的原生 npm 所有命令。

 1,新建文件夹 gulp

 2,切换到gulp目录下,执行 cnpm init,填写相关信息,生成package.json文件;

3,配置package.json 

 1 { 2   "name": "gulp", 3   "version": "1.0.0", 4   "description": "", 5   "main": "index.js", 6   "scripts": { 7     "test": "echo \"Error: no test specified\" && exit 1" 8   }, 9   "author": "lizongqiong",10   "license": "ISC",11   "devDependencies": {12     "browser-sync": "^2.12.12",13     "del": "^1.1.1",14     "gulp": "^3.9.1",15     "gulp-autoprefixer": "^3.1.0",16     "gulp-cache": "^0.4.5",17     "gulp-clean": "^0.3.2",18     "gulp-clean-css": "^2.0.9",19     "gulp-concat": "^2.6.0",20     "gulp-imagemin": "^3.0.1",21     "gulp-plumber": "^1.1.0",22     "gulp-rename": "^1.2.2",23     "gulp-sass": "^2.3.1",24     "gulp-sourcemaps": "^1.6.0",25     "gulp-uglify": "^1.5.3",26     "gulp.spritesmith": "^6.2.1",27     "gulp-connect": "^4.0.0",28     "gulp-csso": "^0.2.6",29     "gulp-if": "^1.2.1",30     "gulp-jshint": "^1.5.3",31     "gulp-load-plugins": "^0.8.0",32     "gulp-minify-html": "^0.1.6",33     "gulp-postcss": "^3.0.0",34     "gulp-size": "^1.1.0",35     "gulp-useref": "^1.0.2",36     "gulp-util": "*",37     "imagemin-pngquant": "^5.0.0"38   }39 }

4,执行cnpm install 安装依赖;

5,新建文件目录如下

技术分享

6,install gulp globally

全局安装 gulp (如果之前进行过 gulp 全局安装,请运行npm rm --global gulp以确保旧版本的 gulp 不与 gulp-cli 相冲突)

$ npm install --global gulp-cli

7,项目开发依赖中安装gulp

$ npm install --save-dev gulp

8,项目根目录创建gulpfile.js

 1 /** 2  * Created by joan on 16/9/29. 3  */ 4 var gulp = require(‘gulp‘); 5 var $ = require(‘gulp-load-plugins‘)(); 6 var connect = require(‘gulp-connect‘); 7 gulp.task(‘webserver‘, function() {    connect.server();}); 8  9 gulp.task(‘js‘, function() {10     gulp.src([‘app/js/test1.js‘, ‘app/js/test2.js‘])11         .pipe($.uglify())12         .pipe($.concat(‘commonJs.js‘))//几个文件的合并13         .pipe(gulp.dest(‘./dist‘));14 15     gulp.src(‘app/js/test.js‘)16         .pipe($.uglify())17         .pipe(gulp.dest(‘./dist‘));18 });19 20 gulp.task(‘css‘, function() {21     gulp.src([‘app/css/test1.css‘, ‘app/css/test2.css‘])22         .pipe($.concat(‘commonCss.css‘))23         .pipe($.csso())24         .pipe(gulp.dest(‘./dist‘));25 26 27     gulp.src([‘app/css/test.css‘])28         .pipe($.csso())29         .pipe(gulp.dest(‘./dist‘));30 });31 32 33 gulp.task(‘clean‘, require(‘del‘).bind(null, [‘.tmp‘, ‘dist‘]));34 gulp.task(‘build‘, [ ‘css‘, ‘js‘], function () {35     return gulp.src(‘dist/**/*‘).pipe($.size({title: ‘build‘, gzip: true}));36 });37 38 /*gulp --vs 1.0.x.x*/39 gulp.task(‘default‘, [‘clean‘], function () {40     gulp.start(‘build‘);41 });

9,执行gulp运行gulpfile.js文件进行打包

$ gulp

10,查看dist目录下就是打包生成的文件

 

基于gulp 的前端自动化构建方案总结