1
votes

I am trying to set up webpack with Babel to compile React files. The webpack config is autogenerated in VSCode with the Webpack extension. I tried adding the "@babel/preset-react" in the presets section, however, it does not work and this error appears:

Module parse failed: Unexpected token (11:16) You may need an appropriate loader to handle this file type.

It appears thar webpack is ignoring the "@babel/preset-react"? The config is as follows.

const path = require('path');
module.exports = {
  mode: 'development',
  entry: path.join(__dirname, 'index.js'),
  watch: true,
  output: {
    path: __dirname + '/dist',
    publicPath: '/dist/',
    filename: "bundle.js",
    chunkFilename: '[name].js'
  },
  module: {
    rules: [{
      test: /.jsx?$/,
      include: [
        path.resolve(__dirname, 'app')
      ],
      exclude: [
        path.resolve(__dirname, 'node_modules')
      ],
      loader: 'babel-loader',
      query: {
        presets: [
          ["@babel/env", {
            "targets": {
              "browsers": "last 2 chrome versions"
            }
          }],
          "@babel/preset-react"
        ]
      }
    }]
  },
  resolve: {
    extensions: ['.json', '.js', '.jsx']
  },
  devtool: 'source-map',
  devServer: {
    contentBase: path.join('/dist/'),
    inline: true,
    host: '0.0.0.0',
    port: 8080,
  }
};

Thank you.

1

1 Answers

1
votes

The loader options are given in the options property in the latest version of Webpack, not query.

You also don't need both the include and exclude properties. The exclude will be enough.

{
  test: /.jsx?$/,
  exclude: /node_modules/,
  loader: "babel-loader",
  options: {
    presets: [
      [
        "@babel/env",
        {
          targets: {
            browsers: "last 2 chrome versions"
          }
        }
      ],
      "@babel/preset-react"
    ]
  }
}