首页 > 代码库 > gulp 编译es6 react 教程 案例 配置

gulp 编译es6 react 教程 案例 配置

1.gulp基本配置:

var gulp = require(‘gulp‘),
	watch = require(‘gulp-watch‘),
	babel = require(‘gulp-babel‘);
var browserify = require(‘gulp-browserify‘);
var SourceMap = require(‘gulp-sourcemaps‘);
var SourceMapSupport = require(‘gulp-sourcemaps-support‘);
gulp.task(‘react‘, () => {
	 gulp.src(‘index.js‘)
		.pipe(SourceMap.init())  //sourcemap只是为了生成代码资源的map
		.pipe(babel({
			presets: [‘es2015‘, ‘es2016‘, ‘es2017‘, ‘stage-0‘, ‘react‘],
			plugins: [‘transform-decorators-legacy‘]
		}))    //这里编译es6代码,包括编译react模板
		.pipe(browserify({
		  insertGlobals : true,
		  debug : !gulp.env.production
		}))   //browserify 的作用就是把require资源从node_modules 里拿出来,然后打包进去到输出的js,如果没有这个插件,那么你不能看到import进来的东西,import的东西没有被打包进去
		.pipe(SourceMap.write(‘.‘))
		.pipe(gulp.dest(‘build‘))
});
gulp.task(‘default‘, () => {
	return watch(‘./index.js‘, function() {
		gulp.run(‘react‘);
	});
});

2.优化 

var gulp = require(‘gulp‘),
	watch = require(‘gulp-watch‘),
	babel = require(‘gulp-babel‘);
var envify = require(‘gulp-envify‘);
var browserify = require(‘gulp-browserify‘);
var SourceMap = require(‘gulp-sourcemaps‘);
var uglify = require(‘gulp-uglifyjs‘);
var SourceMapSupport = require(‘gulp-sourcemaps-support‘);
gulp.task(‘react‘, () => {
	var environment = {
		NODE_ENV: ‘production‘
	};
	gulp.src(‘index.js‘)
		.pipe(SourceMap.init())
		.pipe(babel({
			presets: [‘es2015‘, ‘es2016‘, ‘es2017‘, ‘stage-0‘, ‘react‘],
			plugins: [‘transform-decorators-legacy‘]
		}))
		.pipe(browserify({
			insertGlobals: true,
			debug: !gulp.env.production,
			transformKey: ‘production‘
		}))
		.pipe(envify(environment)) //加入这个插件可以修改代码中的环境等于production
		.pipe(uglify())
		.pipe(SourceMap.write(‘.‘))
		.pipe(gulp.dest(‘build‘))
});
gulp.task(‘default‘, () => {
	return watch(‘./index.js‘, function() {
		gulp.run(‘react‘);
	});
});

  

gulp 编译es6 react 教程 案例 配置