To convert .jsx files to .js files using Gulp and Babel, follow these steps:
- Install Node.js: Ensure Node.js and npm are installed on your system. Download and install from the official Node.js website.
- Initialize the Project: Run the following command in your project root directory to initialize npm and create a
package.jsonfile.
shnpm init -y
- Install Gulp: Install the Gulp CLI (command-line interface) and local Gulp in your project.
shnpm install --save-dev gulp-cli npm install --save-dev gulp
- Install Babel: Install the required Babel dependencies, including the core library, presets, and Gulp plugin.
shnpm install --save-dev @babel/core @babel/preset-react @babel/preset-env gulp-babel
The @babel/preset-react preset is used for converting JSX, while @babel/preset-env is used for converting ES6+ to backward-compatible JavaScript.
- Create the Gulp Configuration File: Create a
gulpfile.jsin your project root directory and configure the Gulp task to use Babel for conversion.
In gulpfile.js, input the following code:
javascriptconst gulp = require('gulp'); const babel = require('gulp-babel'); // Create the Gulp task gulp.task('jsx-to-js', () => { // Specify the source files return gulp.src('src/**/*.jsx') // Initialize sourcemaps .pipe(sourcemaps.init()) // Convert using Babel .pipe(babel({ presets: ['@babel/preset-env', '@babel/preset-react'] })) // Write sourcemaps .pipe(sourcemaps.write('.')) // Specify the output directory .pipe(gulp.dest('dist')); }); // Default task, executed when you run `gulp` gulp.task('default', gulp.series('jsx-to-js'));
- Run the Gulp Task: Execute the following command in your terminal or command line to run the Gulp task, which converts
.jsxfiles to.jsfiles and outputs them to the specified directory.
shgulp
Now, your .jsx files should have been converted to .js files and saved in the dist directory.
Ensure your .jsx files are located in the src directory, as this is the default source directory set in the previous Gulp task. If your .jsx files are stored in a different directory, modify the gulp.src('src/**/*.jsx') part in gulpfile.js to the appropriate directory.
If your project has additional requirements, such as supporting more JavaScript features or integrating other Gulp plugins, you may need to install additional Babel plugins or configure options as needed.