Home  >  Article  >  Web Front-end  >  Convert ES6 code to ES5

Convert ES6 code to ES5

PHPz
PHPzOriginal
2017-04-04 10:32:163017browse

This article introduces using Gulp and Babel 6 to convert ES6 code into ES5 code.

If you use other tools to do it with Babel, you can see here. Don’t know what Gulp is? Please check out the Gulp Getting Started Guide first.

1. InstallationDependencies

Install global Gulp

npm install -g gulp

Install the Gulp used in the project

npm install --save-dev gulp

Install Gulp on Babel Plug-in

npm install --save-dev gulp-babel

Install the plug-in for converting ES6 to ES5 on Babel

npm install --save-dev babel-preset-es2015

2. Gulp configuration

gulpfile.js content, in the form of

var gulp = require("gulp");
var babel = require("gulp-babel");

gulp.task("default", function () {
  return gulp.src("src/**/*.js")// ES6 源码存放的路径
    .pipe(babel()) 
    .pipe(gulp.dest("dist")); //转换成 ES5 存放的路径
});

If you want to generate Sourcemap, use gulp-sourcemaps, in the form of:

var gulp = require("gulp");
var sourcemaps = require("gulp-sourcemaps");
var babel = require("gulp-babel");
var concat = require("gulp-concat");

gulp.task("default", function () {
  return gulp.src("src/**/*.js")
    .pipe(sourcemaps.init())
    .pipe(babel())
    .pipe(concat("all.js"))
    .pipe(sourcemaps.write("."))
    .pipe(gulp.dest("dist"));
});

3. Babel configuration

Create file .babelrc in the project root path. The content is

{
  "presets": ["es2015"]
}

4. Convert

and execute

gulp

in the command line. The complete code can be found here.



The above is the detailed content of Convert ES6 code to ES5. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn