ES6 编译 ES5 环境搭建

旧时模样 提交于 2019-12-06 07:08:53

目录结构

scripts

main.es6
products.es6

temp
gulpfile.js
package.json
index.html

文件内容

package.json

{
  "devDependencies": {
    "browserify": "^11.2.0",
    "gulp": "^3.9.0",
    "gulp-babel": "^5.2.1",
    "gulp-buffer": "0.0.2",
    "gulp-clean": "^0.3.1",
    "gulp-uglify": "^1.4.1",
    "vinyl-source-stream": "^1.1.0"
  }
}

gulpfile.js

var gulp = require('gulp'),
    babel = require('gulp-babel'),
    browserify = require('browserify'),
    source = require('vinyl-source-stream'),
    buffer = require('gulp-buffer'),
    uglify = require('gulp-uglify'),
    clean = require('gulp-clean')
;


gulp.task('help', function () {
    console.log(
`使用帮助:
    gulp bulid  // 编译
`
    )
;
});


/* 编译 */
gulp.task('buildScripts', [
    'buildScriptsES6ToES5',
    'buildScriptsCommonJS',
    'buildScriptsClean'
]);

/* 编译 ES6 为 ES5 */
gulp.task('buildScriptsES6ToES5', function () {
    gulp.src('script/**/*.es6')
        .pipe(babel({modules: 'common'}))
        .pipe(gulp.dest('temp/script'))
    ;
});

/* 编译 CommonJS 脚本 */
gulp.task('buildScriptsCommonJS', function() {
    browserify(['temp/script/main.js'])
        .bundle()
        .pipe(source('main.min.js'))
        .pipe(buffer())
        .pipe(uglify())
        .pipe(gulp.dest('./'))
    ;
});

/* 编译 清理 */
gulp.task('buildScriptsClean', [
    'adminBuildScriptsCommonJS'
], function () {
    gulp.src('temp/script', {read: false})
        .pipe(clean())
    ;
});


gulp.task('default', ['help']);

scripts/main.es6

import {Products} from './products';

let product = new Products();
product.getName();

scripts/products.es6

class Products
{
    getName() {
        console.log('products');
        return 'product';
    }
}

export {Products};

index.html

<!doctype html>
<meta charset="utf-8">
<script src="main.min.js"></script>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!