How to transpile jsx in webpack 4?

Member

by lizzie , in category: Javascript , 6 months ago

How to transpile jsx in webpack 4?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by daisha , 6 months ago

@lizzie 

To transpile JSX in Webpack 4, you need to follow these steps:


Step 1: Install dependencies You will need to install the following dependencies:

  1. babel-loader (transpiles JSX to JavaScript)
  2. @babel/core (core babel library)
  3. @babel/preset-react (preset for transpiling React JSX syntax)


You can install them using npm or yarn:

1
npm install babel-loader @babel/core @babel/preset-react --save-dev


or

1
yarn add babel-loader @babel/core @babel/preset-react --dev


Step 2: Configure the Babel loader In your webpack configuration file, you need to add a rule for JSX files to be transpiled using Babel loader. Here is an example configuration:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
module.exports = {
  // ...other webpack configuration options
  module: {
    rules: [
      // ...other rules,
      {
        test: /.(js|jsx)$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
          options: {
            presets: ["@babel/preset-react"]
          }
        }
      }
    ]
  }
};


Step 3: Create a Babel configuration file Create a .babelrc file in your project's root directory and add the following content to enable the React preset:

1
2
3
{
  "presets": ["@babel/preset-react"]
}


Step 4: Run Webpack Finally, run your webpack build command (e.g. webpack or webpack --watch) and the JSX files will be transpiled to JavaScript during the build process.


This configuration will enable Webpack to transpile JSX syntax to plain JavaScript using Babel.