gulp4配置多页面项目编译打包

又开始公司的新项目了。。。

那当我们拿到公司新项目的时候我们需要做些什么呢? 下面就来分享一下我的工作步骤吧(仅使用于初学者,大神勿见怪- -,有不好的地方希望指出,十分感谢)

1. 整版浏览

这是一个废话的过程。。。但是缺是必不可少的一步,我也不得不说一下

首先预览所有设计图页面,设计需求文案等在脑海中大概的思考一下在哪里需要用到什么,到时候怎么写,还有一些图纸中可能不好实现或者不太清楚的
可以找设计师确认以免到时候耽误时间。

当所有页面全过完之后,回想一下,需要用到哪些技术,哪一些板块是公共的需要提取,哪一些样式是重复的,这些都有个大概思路后可以进行下一步了。

2. 环境搭建

一个好的本地环境,直接决定你的切图码页面流畅度与效率,当然你的扎实的基础功也是必不可少嘛- -。

编辑器需求

适合自己的才是最好的, 我一直用的sublime编辑器,轻量便捷,插件风格都是自己根据喜好与日常需求搭配,当然还有很多好用的编辑器,
例如 : webstorm 这款很强大,基本功能全都有,很重量级但是插件基本都不需要安装了。。。其他的也有一些。只是都没用过,就不来介绍了- -(Atom, Visual Studio Code, Brackets 。。。)

代码环境

我这边用的gulp搭建的环境(已更新到gulp4),我只需要在环境中写h+c+js 保存后页面会直接同步更新我写的页面。 你也可以用webpack或者grunt 搭建你的代码环境,看你喜好

  1. 在中间做了stylus转css并添加前缀然后压缩输出到新的文件夹
  2. 将es6语法js 经过babel转成普通js代码并重命名压缩到新的文件夹
  3. 生成文件打包压缩并添加版本号
  4. 在html中预留位置 自动修改生成的css+js
  5. 在浏览器中同步刷新页面(可多端测试)

那如何搭建这个环境呢? 分享一下我的gulpfile文件 😋

下面事需要依赖的脚本

{
  "name": "new-icon",
  "version": "1.0.0",
  "description": "new icon project",
  "main": "gulpfile.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.5.5",
    "@babel/plugin-transform-runtime": "^7.5.5",
    "@babel/preset-env": "^7.5.5",
    "@babel/runtime": "^7.5.5",
    "babel-loader": "^8.0.6",
    "babel-polyfill": "^6.26.0",
    "babelify": "^10.0.0",
    "browser-sync": "^2.26.7",
    "del": "^5.0.0",
    "gulp": "^4.0.2",
    "gulp-autoprefixer": "^6.1.0",
    "gulp-babel": "^8.0.0",
    "gulp-changed": "^4.0.0",
    "gulp-rename": "^1.4.0",
    "gulp-rev": "^9.0.0",
    "gulp-rev-collector": "^1.3.1",
    "gulp-stylus": "^2.7.0",
    "vinyl-buffer": "^1.0.1",
    "vinyl-named": "^1.1.0",
    "vinyl-source-stream": "^2.0.0",
    "webpack": "^4.38.0",
    "webpack-stream": "^5.2.1"
  },
  "dependencies": {
    "core-js": "^2.6.9",
    "gulp-clean-css": "^4.2.0",
    "gulp-htmlmin": "^5.0.1",
    "gulp-less": "^4.0.1",
    "jquery": "^3.4.1",
    "jquery-colpick": "^3.1.0",
    "jquery-confirm": "^3.3.4",
    "less-plugin-autoprefix": "^2.0.0",
    "lord-icon-element": "^1.0.0",
    "lottie-web": "^5.5.7",
    "qrcode": "^1.4.1"
  }
}


这是我的package.json中的一些插件依赖

在gulp配置中我的代码如下

const gulp = require('gulp');
const browserSync = require('browser-sync').create();
const less = require('gulp-less');
const LessAutoprefix = require('less-plugin-autoprefix');
const compressCss = require('gulp-clean-css');
const rename = require('gulp-rename');
const gulpWebpack = require('webpack-stream');
const webpack = require('webpack');
const named = require('vinyl-named');
const rev = require('gulp-rev');
const del = require('del');
const minHtml = require('gulp-htmlmin');
const changed = require('gulp-changed');
const revCollector = require('gulp-rev-collector');
const webpackConfig = require('./webpack.config');
const stylus = require('gulp-stylus');
const prefixer = require('gulp-autoprefixer');

let autoprefix = new LessAutoprefix({
	browsers: [
		">0.25%",
		"last 2 version",
	]
});

// 域名
let hostname = '285z';

// 项目目录
const filePath = 'bookdd/book' + hostname + '/';
// 端类型
let host_type = 'm';

// 生产目录
const fileDistPath = 'xs_cms/pub_' + host_type + hostname + '/assets/';
const filePagesPath = 'xs_cms/app/' + host_type + '_novel' + hostname + '/view/';
const fileSrc = host_type == 'm' ? '/assets/' : 'https://mip.' + hostname + '.com/assets/';

// 开发目录
// const fileDistPath = filePath + 'dist/assets/';
// const filePagesPath = filePath + 'dist/pages/';
// const fileSrc = '/assets/';


gulp.task('cleanCSS', () => {
	return del([
		fileDistPath + 'css'
	])
})

gulp.task('cleanJS', () => {
	return del([
		fileDistPath + 'js'
	])
})

gulp.task('cleanHTML', () => {
	return del([
		filePagesPath
	])
})

// 编译并压缩js
gulp.task('compileJs', gulp.series('cleanJS', () => {
	return gulp.src(filePath + 'es6/*.js')
		.pipe(changed(fileDistPath + 'js'))
		.pipe(named())
		.pipe(gulpWebpack(webpackConfig, webpack))
		.pipe(rename(function (path) {
			path.basename += '.min';
		}))
		.pipe(rev())
		.pipe(gulp.dest(fileDistPath + 'js'))
		.pipe(rev.manifest())
		.pipe(gulp.dest(filePath + 'mapjson/js'))
		.pipe(browserSync.reload({
			stream: true
		}));
}))

// 合并并压缩less => css
gulp.task('convertCSS', gulp.series('cleanCSS', () => {
	return gulp.src(filePath + 'less/*.less')
		.pipe(changed(fileDistPath + 'css', {
			extension: '.css'
		}))
		.pipe(less({
			plugins: [autoprefix]
		}))
		.pipe(compressCss())
		.pipe(rename(function (path) {
			path.basename += '.min';
		}))
		.pipe(rev())
		.pipe(gulp.dest(fileDistPath + 'css'))
		.pipe(rev.manifest())
		.pipe(gulp.dest(filePath + 'mapjson/css'))
		.pipe(browserSync.reload({
			stream: true
		}));
}))

// 合并并压缩stylus => css
gulp.task('convertStylus', gulp.series('cleanCSS', () => {
	return gulp.src(filePath + 'stylus/*.styl')
		.pipe(changed(fileDistPath + 'css', {
			extension: '.css'
		}))
		.pipe(stylus({
			compress: true
		}))
		.pipe(prefixer({
			overrideBrowserslist: [
				"Android 4.1",
				"iOS 7.1",
				"Chrome > 31",
				"ff > 31",
				"ie >= 8"
			],
			grid: true,
			cascade: false
		}))
		.pipe(rename(function (path) {
			path.basename += '.min';
		}))
		.pipe(rev())
		.pipe(gulp.dest(fileDistPath + 'css'))
		.pipe(rev.manifest())
		.pipe(gulp.dest(filePath + 'mapjson/css'))
		.pipe(browserSync.reload({
			stream: true
		}));
}))
const hbAttrWrapOpen = /\{\% if[^}]+\%\}/;
const hbAttrWrapClose = /\{\%[^}]+endif \%\}/;
const hbAttrWrapPair = [hbAttrWrapOpen, hbAttrWrapClose];
// less => 'convertCSS',  stylus => 'convertStylus',
gulp.task('revHtml', gulp.series(gulp.parallel('convertStylus', 'compileJs'), () => {
	return gulp.src([filePath + 'mapjson/*/*.json', filePath + (host_type == 'm' ? 'pages' : 'mippages') + '/*/*.twig'])
		.pipe(revCollector({
			replaceReved: true,
			dirReplacements: {
				'js': fileSrc + 'js/',
				'css': fileSrc + 'css/'
			}
		}))
		.pipe(minHtml({
			collapseWhitespace: true,
			removeComments: true,
			removeEmptyAttributes: true,
			customAttrSurround: [hbAttrWrapPair],
			ignoreCustomFragments: [hbAttrWrapOpen]
		}))
		.pipe(gulp.dest(filePagesPath))
		.pipe(browserSync.reload({
			stream: true
		}));
}))

gulp.task('freshHtml', () => {
	return gulp.src([filePath + 'mapjson/*/*.json', filePath + (host_type == 'm' ? 'pages' : 'mippages') + '/*/*.twig'])
		.pipe(changed(filePagesPath))
		.pipe(revCollector({
			replaceReved: true,
			dirReplacements: {
				'js': fileSrc + 'js/',
				'css': fileSrc + 'css/'
			}
		}))
		.pipe(minHtml({
			collapseWhitespace: true,
			removeComments: true,
			removeEmptyAttributes: true,
			customAttrSurround: [hbAttrWrapPair],
			ignoreCustomFragments: [hbAttrWrapOpen]
		}))
		.pipe(gulp.dest(filePagesPath))
		.pipe(browserSync.reload({
			stream: true
		}));
})

gulp.task('copyimgs', () => {
	return gulp.src(filePath + 'images/*')
		.pipe(gulp.dest(fileDistPath + 'images'))
		.pipe(browserSync.reload({
			stream: true
		}));
})

gulp.task('copyfile', () => {
	return gulp.src(filePath + 'fonts/icomoon.*')
		.pipe(gulp.dest(fileDistPath + 'fonts'))
})

gulp.task('cleanDist', () => {
	return del([filePath + 'dist'])
})

// 监视文件变化,自动执行任务
gulp.task('watch', () => {
	browserSync.init(
		// {
		// 	server: {
		// 		baseDir: filePath
		// 	}
		// }
	);
	// gulp.watch(filePath + 'less/**/*.less', gulp.series('revHtml'));
	gulp.watch(filePath + 'stylus/**/*.styl', gulp.series('revHtml'));
	gulp.watch(filePath + 'es6/**/*.js', gulp.series('revHtml'));
	gulp.watch(filePath + (host_type == 'm' ? 'pages' : 'mippages') + '/*/*.twig', gulp.series('freshHtml'));
	gulp.watch(filePath + 'images/*', gulp.series('copyimgs'));
})

gulp.task('start', gulp.series(gulp.parallel('watch', 'revHtml', 'copyfile', 'copyimgs')));


webpack配置文件

webpack.config.js文件

const webpack = require('webpack');

module.exports = {
    mode: 'production',
    // devtool: 'source-map',
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /(node_modules|bower_components)/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: ['@babel/preset-env'],
                        plugins:[
                            "@babel/plugin-transform-runtime",
                            "@babel/plugin-transform-modules-commonjs",
                        ]
                    }
                }
            }
        ]
    },
    plugins: [
        new webpack.ProvidePlugin({
            $: "jquery", // npm
            jQuery: "jquery", // 本地Js文件
        })
    ]
}

这些配置好之后,你只要在git bush中运行gulp start 就OK啦,当然这里你文件结构还没有哦。。。你只需一个这样的文件结构就好啦

-node_moules

-gulpfile,js

-webpack.config.js

-dist(会生成的文件目录)

-src
    -css
        -*.css
    -js
        -*.js
    -pages
        -*.html

-package.json

项目已经上线,www.macw.com ,你可以在线预览网站效果与功能,有问题可以给我留言哈,支持给个关注吧

上面就完成你的代码环境配置啦,可以开始愉快的敲代码了,你可以在第一次运行后发现生成的dist文件,这里面你也可以放入你需要的静态资源与第三方文件哦,后期项目可以直接拿dist文件就好啦。

posted @ 2019-01-10 17:05  前端MRzhu  阅读(2134)  评论(2编辑  收藏  举报