目录
项目结构
Gulp
Gulp是一个自动化构建工具,可以帮助前端开发者通过自动化任务来管理工作流程。Gulp使用Node.js的代码编写,可以更加灵活地管理代码以及任务流程.
对于Vue.js前端框架,使用Gulp并不是必须的,因为Vue.js提供了Vue-cli,可以帮助前端开发者快速搭建项目以及项目的构建环境。Vue-cli是一个基于Webpack的脚手架工具,可以快速创建Vue.js应用程序,并且帮助生成项目骨架以及构建系统。其内置了webpack、Babel、ESLint等工具,可以方便地进行模块打包、ES6转换、代码检查等。使用Vue-cli,可以弹性地对项目进行管理和构建。
但是对于一些需要个性化开发的开发者来说,Vue-cli的功能是不够的。前端开发者需要使用其他的构建工具来满足他们的需求,比如Gulp。使用Gulp可以帮助开发者扩展Vue-cli的功能,同时使构建流程更加简单,例如使用Gulp可以定制SASS/LESS文件编译、CSS文件合并压缩、JS文件压缩混淆、图片压缩等等。这样可以方便地定制应用程序及其构建流程,同时减少重复操作。
而且,使用Gulp也可以减少构建速度。Vue-cli虽然帮助我们构建了项目骨架以及构建环境,但是在打包大规模的代码时,打包速度较慢。使用Gulp可以在webpack后处理流程中进行Sass编译、Html统一压缩等操作,并提高构建速度。
总之,对于Vue.js前端框架,使用Gulp并不是必须的,但是它提供了扩展功能、使构建流程更加简单、加快了打包速度等优点。使用Gulp进行项目的构建可以为前端开发者节省时间、精力,并且优化构建方式。因此,个性化开发需要Gulp的前端开发者可以使用它对Vue-cli进行扩展,而其余开发者可以继续使用Vue-cli快速构建Vue.js应用程序。
VUE使用Gulp
Vue安装Gulp
首先,我们需要安装所需的依赖。我们需要全局安装Gulp,通过npm命令安装:
npm install -g gulp-cli
接下来,我们需要在项目根目录下安装Gulp和其他依赖(比如babel、browserify等):
npm install gulp babelify browserify gulp-babel gulp-rename gulp-sourcemaps gulp-uglify vinyl-buffer vinyl-source-stream vueify --save-dev
Vue定义Gulp.js
gulpfile.js代码如下:
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var path = require('path');
var del = require('del');
var version = ''; // 版本号
var versionPath = ''; // 版本号路径
// prod-运行环境 qa-测试环境
var env = process.env.npm_config_qa ? 'qa' : process.env.npm_config_uat ? 'uat' : 'prod';
// 文件夹
var distPath = path.resolve('./dist');
// 创建版本号(年月日时分)
(function () {
var d = new Date();
var yy = d.getFullYear();
var MM = d.getMonth() + 1 >= 10 ? (d.getMonth() + 1) : '0' + (d.getMonth() + 1);
var DD = d.getDate() >= 10 ? d.getDate() : '0' + d.getDate();
var h = d.getHours() >= 10 ? d.getHours() : '0' + d.getHours();
var mm = d.getMinutes() >= 10 ? d.getMinutes() : '0' + d.getMinutes();
version = "" + yy + MM + DD + h + mm;
versionPath = distPath + '/' + version;
})();
// 编译
if('qa'===env){
gulp.task('build', $.shell.task([ 'node build/build-qa.js' ]));
}else if('prod'===env){
gulp.task('build', $.shell.task([ 'node build/build-prod.js' ]));
}
// 创建版本号目录
gulp.task('create:versionCatalog', function () {
return gulp.src(`${distPath}/static/**/*`)
.pipe(gulp.dest(`${versionPath}/static/`))
});
// 替换${versionPath}/static/js/manifest.js window.SITE_CONFIG.cdnUrl占位变量
gulp.task('replace:cdnUrl', function () {
return gulp.src(`${versionPath}/static/js/manifest.js`)
.pipe(.replace(new RegExp(\`"{require('./config').build.assetsPublicPath}"`, 'g'), 'window.SITE_CONFIG.cdnUrl + "/"'))
.pipe(gulp.dest(`${versionPath}/static/js/`))
});
// 替换{versionPath}/static/config/index-{env}.js window.SITE_CONFIG['version']配置变量
gulp.task('replace:version', function () {
return gulp.src(`{versionPath}/static/config/index-{env}.js`)
.pipe(.replace(/window.SITE_CONFIG\\\['version'\\\] = '.\*'/g, \`window.SITE_CONFIG\['version'\] = '{version}'`))
.pipe(gulp.dest(`${versionPath}/static/config/`))
});
// 合并{versionPath}/static/config/\[index-{env}, init].js 至 ${distPath}/config/index.js
gulp.task('concat:config', function () {
return gulp.src([`{versionPath}/static/config/index-{env}.js`, `${versionPath}/static/config/init.js`])
.pipe($.concat('index.js'))
.pipe(gulp.dest(`${distPath}/config/`))
});
//清除, 编译 / 处理项目中产生的文件
gulp.task('cleanBuild', function () {
return del([`{distPath}/static\`, \`{versionPath}/static/config`])
});
// 清空
gulp.task('clean', function () {
return del([versionPath])
});
//gulp.series|4.0 依赖
//gulp.parallel|4.0 多个依赖嵌套
gulp.task('default',gulp.series(gulp.series('build','create:versionCatalog','replace:cdnUrl','replace:version','concat:config','cleanBuild')));
package.json
build------打包正式环境
build:qa----打包测试环境
build文件夹
build-prod 、webpack.prod.confi.js 正式
build-qa 、webpack.qa.conf.js 测试
build-prod.js代码
'use strict'
require('./check-versions')()
process.env.NODE_ENV = 'production'
const ora = require('ora')
const rm = require('rimraf')
const path = require('path')
const chalk = require('chalk')
const webpack = require('webpack')
const config = require('../config')
const webpackConfig = require('./webpack.prod.conf')
const spinner = ora('building for production...')
spinner.start()
rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => {
if (err) throw err
webpack(webpackConfig, (err, stats) => {
spinner.stop()
if (err) throw err
process.stdout.write(stats.toString({
colors: true,
modules: false,
children: false,
chunks: false,
chunkModules: false
}) + '\n\n')
if (stats.hasErrors()) {
console.log(chalk.red(' Build failed with errors.\n'))
process.exit(1)
}
console.log(chalk.cyan(' Build complete.\n'))
console.log(chalk.yellow(
' Tip: built files are meant to be served over an HTTP server.\n' +
' Opening index.html over file:// won\'t work.\n'
))
})
})
build-qa.js代码
'use strict'
require('./check-versions')()
process.env.NODE_ENV = 'production'
const ora = require('ora')
const rm = require('rimraf')
const path = require('path')
const chalk = require('chalk')
const webpack = require('webpack')
const config = require('../config')
const webpackConfig = require('./webpack.qa.conf')
const spinner = ora('building for production...')
spinner.start()
rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => {
if (err) throw err
webpack(webpackConfig, (err, stats) => {
spinner.stop()
if (err) throw err
process.stdout.write(stats.toString({
colors: true,
modules: false,
children: false,
chunks: false,
chunkModules: false
}) + '\n\n')
if (stats.hasErrors()) {
console.log(chalk.red(' Build failed with errors.\n'))
process.exit(1)
}
console.log(chalk.cyan(' Build complete.\n'))
console.log(chalk.yellow(
' Tip: built files are meant to be served over an HTTP server.\n' +
' Opening index.html over file:// won\'t work.\n'
))
})
})
webpack.prod.conf.js
'use strict'
const path = require('path')
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
const merge = require('webpack-merge')
const baseWebpackConfig = require('./webpack.base.conf')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
const env =require('../config/prod.env')
const webpackConfig = merge(baseWebpackConfig, {
module: {
rules: utils.styleLoaders({
sourceMap: config.build.productionSourceMap,
extract: true,
usePostCSS: true
})
},
devtool: config.build.productionSourceMap ? config.build.devtool : false,
output: {
path: config.build.assetsRoot,
filename: utils.assetsPath('js/[name].js'),
chunkFilename: utils.assetsPath('js/[id].js')
},
plugins: [
new webpack.DefinePlugin({
'process.env': env
}),
new UglifyJsPlugin({
uglifyOptions: {
compress: {
warnings: false
}
},
sourceMap: config.build.productionSourceMap,
parallel: true
}),
// extract css into its own file
new ExtractTextPlugin({
filename: utils.assetsPath('css/[name].css'),
allChunks: false,
}),
new OptimizeCSSPlugin({
cssProcessorOptions: config.build.productionSourceMap
? { safe: true, map: { inline: false } }
: { safe: true }
}),
new HtmlWebpackPlugin({
filename: process.env.NODE_ENV === 'testing'? 'index.html' : config.build.index,
template: 'index.html',
inject: false,
minify: {
removeComments: true,
collapseWhitespace: true,
removeAttributeQuotes: true
},
chunksSortMode: 'dependency'
}),
new webpack.HashedModuleIdsPlugin(),
new webpack.optimize.ModuleConcatenationPlugin(),
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks (module) {
// any required modules inside node_modules are extracted to vendor
return (
module.resource &&
/\.js$/.test(module.resource) &&
module.resource.indexOf(
path.join(__dirname, '../node_modules')
) === 0
)
}
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'manifest',
minChunks: Infinity
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'app',
async: 'vendor-async',
children: true,
minChunks: 3
}),
// copy custom static assets
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, '../static'),
to: config.build.assetsSubDirectory,
ignore: ['.*']
}
])
]
})
if (config.build.productionGzip) {
const CompressionWebpackPlugin = require('compression-webpack-plugin')
webpackConfig.plugins.push(
new CompressionWebpackPlugin({
asset: '[path].gz[query]',
algorithm: 'gzip',
test: new RegExp(
'\\.(' +
config.build.productionGzipExtensions.join('|') +
')$'
),
threshold: 10240,
minRatio: 0.8
})
)
}
if (config.build.bundleAnalyzerReport) {
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
webpackConfig.plugins.push(new BundleAnalyzerPlugin({ analyzerMode: 'static' }))
}
module.exports = webpackConfig
webpack.qa.conf.js代码
'use strict'
const path = require('path')
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
const merge = require('webpack-merge')
const baseWebpackConfig = require('./webpack.base.conf')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
const env =require('../config/qa.env')
const webpackConfig = merge(baseWebpackConfig, {
module: {
rules: utils.styleLoaders({
sourceMap: config.build.productionSourceMap,
extract: true,
usePostCSS: true
})
},
devtool: config.build.productionSourceMap ? config.build.devtool : false,
output: {
path: config.build.assetsRoot,
filename: utils.assetsPath('js/[name].js'),
chunkFilename: utils.assetsPath('js/[id].js')
},
plugins: [
new webpack.DefinePlugin({
'process.env': env
}),
new UglifyJsPlugin({
uglifyOptions: {
compress: {
warnings: false
}
},
sourceMap: config.build.productionSourceMap,
parallel: true
}),
new ExtractTextPlugin({
filename: utils.assetsPath('css/[name].css'),
allChunks: false,
}),
new OptimizeCSSPlugin({
cssProcessorOptions: config.build.productionSourceMap
? { safe: true, map: { inline: false } }
: { safe: true }
}),
new HtmlWebpackPlugin({
filename: process.env.NODE_ENV === 'testing'
? 'index.html'
: config.build.index,
template: 'index.html',
inject: false,
minify: {
removeComments: true,
collapseWhitespace: true,
removeAttributeQuotes: true
},
chunksSortMode: 'dependency'
}),
new webpack.HashedModuleIdsPlugin(),
new webpack.optimize.ModuleConcatenationPlugin(),
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks (module) {
return (
module.resource &&
/\.js$/.test(module.resource) &&
module.resource.indexOf(
path.join(__dirname, '../node_modules')
) === 0
)
}
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'manifest',
minChunks: Infinity
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'app',
async: 'vendor-async',
children: true,
minChunks: 3
}),
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, '../static'),
to: config.build.assetsSubDirectory,
ignore: ['.*']
}
])
]
})
if (config.build.productionGzip) {
const CompressionWebpackPlugin = require('compression-webpack-plugin')
webpackConfig.plugins.push(
new CompressionWebpackPlugin({
asset: '[path].gz[query]',
algorithm: 'gzip',
test: new RegExp(
'\\.(' +
config.build.productionGzipExtensions.join('|') +
')$'
),
threshold: 10240,
minRatio: 0.8
})
)
}
if (config.build.bundleAnalyzerReport) {
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
webpackConfig.plugins.push(new BundleAnalyzerPlugin({ analyzerMode: 'static' }))
}
module.exports = webpackConfig
config文件夹
prod.env.js代码
'use strict'
module.exports = {
NODE_ENV: '"production"'
}
qa.env.js代码
'use strict'
module.exports = {
NODE_ENV: '"production"'
}
static-config文件夹
index-prod.js代码
/**
* 生产环境
*/
; (function () {
window.SITE_CONFIG = {};
// api接口请求地址
window.SITE_CONFIG['baseUrl'] = 'xxxxxx';
// cdn地址 = 域名 + 版本号
window.SITE_CONFIG['domain'] = './'; // 域名
window.SITE_CONFIG['version'] = ''; // 版本号(年月日时分)
window.SITE_CONFIG['cdnUrl'] = window.SITE_CONFIG.domain + window.SITE_CONFIG.version;
})();
index-qa.js
/**
* 测试环境
*/
; (function () {
window.SITE_CONFIG = {};
// api接口请求地址
window.SITE_CONFIG['baseUrl'] = 'xxxxxxxx';
// cdn地址 = 域名 + 版本号
window.SITE_CONFIG['domain'] = './'; // 域名
window.SITE_CONFIG['version'] = ''; // 版本号(年月日时分)
window.SITE_CONFIG['cdnUrl'] = window.SITE_CONFIG.domain + window.SITE_CONFIG.version;
})();
以上是gulf 打包的代码。