Gulp和Webpack简单入门
Gulp:http://www.gulpjs.com.cn/
Webpack:https://my.oschina.net/u/2562868/blog/856983
Gulp和Webpack 结合使用
首先我们将我已经写好的一个样本clone下来
git clone https://github.com/thomaslwq/webpack-react-redux.git
然后执行
npm install
npm start
安装完依赖之后,打开http://localhost:3000/,就可以访问了。
在根目录下面运行 gulp dev生成开发版本,gulp prod生成生产版本,默认是在生成在根目录下的dist目录。
为什么会这样子呢?我们先看一段代码gulp代码
在工程目录下来有一个gulpfile.js,里面定义了两个gulp命令。
当执行gulp dev的时候,会执行webpack --config webpack.config.js命令,
当执行gulp prod的时候,会执行webpack --config webpack.production.config.js 命令。
看到这里,有人会说那我直接运行这些命令就行了,干嘛还要使用 gulp 呢?
其实gulp实现的功能不只只这些,webpack只是一个静态资源打包工具,如果我们有其它的功能,类似压缩,发布,备份等等功能要实现,那么webpack 就显得力不从从心了。例如,我们现在要实现对打包之后的dist文件进行压缩。这里我们要用到一个gulp-zip,del和gulp-sequence的插件。实现代码如下,
/**
* @author Thomas.Lin
* @version 1.0
* 2017-05-09
* usage:
* run "gulp prod" will create the product version,
* run "gulp dev" will create the development version.
*
*/
var gulp = require('gulp'),
webpack = require('webpack'),
zip = require("gulp-zip"),
del = require("del"),
gulpSequence = require("gulp-sequence");
//clean dist folder before
gulp.task("clean",function( done ){
return del(["dist.zip","dist"],done);
});
//create a zip
gulp.task("zip",function( done ){
gulp.src("./dist/**/*").pipe(zip("./dist.zip")).pipe(gulp.dest("./"));
});
//build dev js
//use the local command to execute webpack
gulp.task("build-dev", function(){
return require("child_process").
execSync('webpack --config webpack.config.js',
{
stdio:[0,1,2]
});
});
gulp.task("build-prod", function(){
return require("child_process").
execSync('webpack --config webpack.production.config.js',
{
stdio:[0,1,2]
});
});
//execute by sequence
gulp.task("dev",function(done){
gulpSequence("clean","build-dev","zip",done)
});
gulp.task("prod",function(done){
gulpSequence("clean","build-prod","zip",done)
});
这样一来,我们就实现了清除,编译,打包,压缩。
当然,如果你还有一个版本管理的Maven仓库,你还可以通过gulp将生成的源码传到仓库里面,使用的是gulp的maven-deploy插件,实现样例如下:
var maven = require('maven-deploy');
var config = {
"groupId" : "com.example", // required - the Maven group id.
"artifactId" : "{name}", // the Maven artifact id.
"buildDir" : "dist", // project build directory.
"finalName" : "{name}", // the final name of the file created when the built project is packaged.
"type" : "war", // type of package. "war" or "jar" supported.
"fileEncoding" : "utf-8" // file encoding when traversing the file system, default is UTF-8
"repositories" : [ // array of repositories, each with id and url to a Maven repository.
{
"id": "example-internal-snapshot",
"url": "http://mavenproxy.example.com/example-internal-snapshot/"
},
{
"id": "example-internal-release",
"url": "http://mavenproxy.example.com/example-internal-release/"
}
]
};
maven.config(config);
maven.deploy('example-internal-snapshot', true);
也可以参考:https://www.npmjs.com/package/maven-deploy