alexW
alexW

Reputation: 193

The babel preset @babel/preset-react doesn't like my javascript function that returns a JS.X element

I have a .js file with react imported with a function that returns a span tag like so:

makeSpan = (number, prefix) => { 
  return <span>{prefix} {number}</span>
};

I will require this .js file to my react class and call it to render the span. The problem is that webpack is giving my syntax error unexpected token and apparently it's something to do with JSX syntax (returning a span)

webpack.config.js

const path = require('path')
HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
  entry: './src/index.js',
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'index_bundle.js',
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader'
        }
      },
      {
        test:/\.css$/,
        use:['style-loader','css-loader']
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/template.html'
    })
  ]
}

babelrc

{  
  "presets": ["@babel/preset-env", "@babel/preset-react"],
  "plugins": ["@babel/plugin-proposal-class-properties"]
}

Upvotes: 1

Views: 886

Answers (1)

alexW
alexW

Reputation: 193

I solved this problem my solution was to put babel plugins in webpack.config.js as well. I don't know why it works this way.

module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ["@babel/preset-env", "@babel/preset-react"],
            plugins: ["@babel/plugin-proposal-class-properties"]
          }
        }
      },
      {
        test:/\.css$/,
        use:['style-loader','css-loader']
      }
    ]
  },

Upvotes: 1

Related Questions