To use ES6 Code in your application, we need to transpile the ES6 code into ES5 code using babel so that it can be understood by different as well as old browsers.
Step 1: Install Necessary Packages
npm install @babel/core @babel/preset-env gulp-babel --save-dev
If you encounter an error like this:
ReferenceError: primordials is not defined in node...
Then it will be helpful to update gulp to version 4. I was using node@12 and gulp@3. To update gulp run the below command :
npm install gulp@4 --save-dev
Note: async and series() are for gulp 4
Step 2: Now, tell our project to use babel (you can use A or B option)
A) In your package.json file, add this code after dependencies and devDependencies
{
“presets”: [“@babel/preset-env”]
}
B) Make a .babelrc
file in your root directory and add the below code.
{
“presets”: [“@babel/preset-env”]
}
Step 3: Add the dependency for babel in the file:
gulpfile.js
You may need to rename the gulpfile.js
file to gulpfile.babel.js.
Add the following code in gulpfile.js
to include gulp and babel dependency:
var gulp = require('gulp'),
require('gulp-babel')
Step 4: Define which all files we have to transpile :
var requiredFiles = ['modules/**/*.js', // include these files
'!js/vendors/**/*.js', // exclude these files
Step 5: Pass it as the source to gulp:
gulp.task('babelTest', async function () {
return gulp.src(requiredFiles)
.pipe(babel({presets: ['@babel/preset-env'] }))
.pipe(gulp.dest('dist/js'));
});
Step 6: To run the gulp task while gulp build:
gulp.task('build', gulp.series('babelTest', ....));
And run the build using the below command, it should now perform transpilation also along with other tasks that you want to run during the build.
npm run build
(Optional) Step 7: To run babelTest task from npm:
In your package.json
file add below code inside scripts:
"scripts":{
"babelTest": "gulp babelTest",
}
And to just run the babel transpilation type below code in terminal:
npm run babelTest
Remember:
The ES6 -> ES5 conversion should have before the uglification of code because uglification cannot understand the ES6 syntax.
Ex:
var gulp = require('gulp'),
uglifyJS = require('gulp-uglify'),
babel = require('gulp-babel');....gulp.task('uglifyJS', async function () {
gulp.src(requiredFiles)
.pipe(babel({presets: ['@babel/preset-env'] }))
.pipe(uglifyJS())
.pipe(gulp.dest('dist/js'));
});.....
If you like my story or it helped you. You can buy me a coffee: