乐闻世界logo
搜索文章和话题

How convert .jsx to .js with Gulp and Babel?

1个答案

1

To convert .jsx files to .js files using Gulp and Babel, follow these steps:

  1. Install Node.js: Ensure Node.js and npm are installed on your system. Download and install from the official Node.js website.
  2. Initialize the Project: Run the following command in your project root directory to initialize npm and create a package.json file.
sh
npm init -y
  1. Install Gulp: Install the Gulp CLI (command-line interface) and local Gulp in your project.
sh
npm install --save-dev gulp-cli npm install --save-dev gulp
  1. Install Babel: Install the required Babel dependencies, including the core library, presets, and Gulp plugin.
sh
npm 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.

  1. Create the Gulp Configuration File: Create a gulpfile.js in your project root directory and configure the Gulp task to use Babel for conversion.

In gulpfile.js, input the following code:

javascript
const 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'));
  1. Run the Gulp Task: Execute the following command in your terminal or command line to run the Gulp task, which converts .jsx files to .js files and outputs them to the specified directory.
sh
gulp

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.

2024年6月29日 12:07 回复

你的答案