Skip to content

babel-loader 6.2.1 does not recognize JSX syntax #198

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
pkosenko opened this issue Jan 12, 2016 · 24 comments
Closed

babel-loader 6.2.1 does not recognize JSX syntax #198

pkosenko opened this issue Jan 12, 2016 · 24 comments

Comments

@pkosenko
Copy link

Reference Stackoverflow (the topic has comments disabled):

http://stackoverflow.com/questions/33460420/babel-loader-jsx-syntaxerror-unexpected-token

None of the answers in this post seem to work for me. I was compiling straight from Babel 5 (babel app.js -o bundle.js) with no problem. But when I attempted to switch over to webpack with Babel 6 with a webpack.config.js file, all of a sudden the babel-loader was having trouble recognizing JSX syntax embedded in the main app.js file.
Line 70: Unexpected token <
You may need an appropriate loader to handle this file type. ???????
| return (
|

So there is something screwed up in webpack or babel-loader.

Adding "react" presets to the .babelrc file or to the webpack.config.js files does NOT solve the problem as was indicated in the Stackoverflow. That suggests that there is something broken with the babel-loader version that I am using.

I have global install of Babel version 5.8.23 (babel-core 5.8.24) vs. local webpack install of "babel-loader" version 6.2.1.

@Couto
Copy link
Member

Couto commented Jan 15, 2016

Can you share your .babelrc, webpack.config.js and package.json please?

@RubenCordeiro
Copy link

I am having exactly the same issue.

Here are the contents of my files:

.babelrc

{
  "presets": ["es2015", "react"]
}

webpack.config.js

'use strict';

const HtmlPlugin = require('html-webpack-plugin');

module.exports = {
    loaders: [
        {
            test: /\.jsx?$/,
            loader: 'babel',
            exclude: /node_modules/,
            query: {
                presets: ['es2015', 'react']
            }
        },
        {
            test: /\.scss$/,
            loader: 'style!css!sass!sass-resources'
        },
        {
            test: /bootstrap\/dist\/js\/umd\//,
            loader: 'imports?jQuery=jquery'
        },
        { test: /\.(woff2?|svg)$/, loader: 'url?limit=10000' },
        { test: /\.(ttf|eot)$/, loader: 'file' }
    ],
    plugins: [new HtmlPlugin({
        title: 'CustomTitle',
        template: 'index.html', // Load a custom template
        inject: 'body' // Inject all scripts into the body
    })],
    entry: './src/index.jsx',
    output: {
        path: `${__dirname}/dist`,
        filename: 'bundle.js'
    }
};

package.json

{
  "name": "my-client",
  "version": "0.1.0",
  "description": "Blablablah",
  "scripts": {
    "build": "webpack --progress --colors",
    "dev": "webpack-dev-server --progress --colors",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "customKeyword"
  ],
  "author": "Ruben Cordeiro",
  "license": "UNLICENSED",
  "dependencies": {
    "babel-core": "6.4.0",
    "babel-loader": "6.2.1",
    "babel-plugin-transform-es2015-modules-commonjs": "6.4.0",
    "babel-preset-es2015": "6.3.13",
    "babel-preset-react": "6.3.13",
    "bootstrap": "4.0.0-alpha.2",
    "bootstrap-loader": "1.0.5",
    "bootstrap-sass": "3.3.6",
    "css-loader": "0.23.1",
    "file-loader": "0.8.5",
    "html-webpack-plugin": "1.7.0",
    "imports-loader": "0.6.5",
    "node-sass": "3.4.2",
    "react": "0.14.6",
    "react-dom": "0.14.6",
    "react-redux": "4.0.6",
    "redux": "3.0.5",
    "redux-devtools": "3.0.1",
    "resolve-url-loader": "1.4.3",
    "sass-loader": "3.1.2",
    "sass-resources-loader": "1.0.1",
    "style-loader": "0.13.0",
    "url-loader": "0.5.7",
    "webpack": "1.12.11"
  }
}

@Couto
Copy link
Member

Couto commented Jan 17, 2016

@RubenCordeiro Your webpack config is wrong :)

'use strict';

const HtmlPlugin = require('html-webpack-plugin');

module.exports = {
    module: {
        loaders: [
            {
                test: /\.jsx?$/,
                loader: 'babel',
                exclude: /node_modules/,
                query: {
                    presets: ['react', 'es2015']
                }
            },
            {
                test: /\.scss$/,
                loader: 'style!css!sass!sass-resources'
            },
            {
                test: /bootstrap\/dist\/js\/umd\//,
                loader: 'imports?jQuery=jquery'
            },
            { test: /\.(woff2?|svg)$/, loader: 'url?limit=10000' },
            { test: /\.(ttf|eot)$/, loader: 'file' }
        ],
    },
    plugins: [new HtmlPlugin({
        title: 'CustomTitle',
        template: 'index.html', // Load a custom template
        inject: 'body' // Inject all scripts into the body
    })],
    entry: './src/index.jsx',
    output: {
        path: `${__dirname}/dist`,
        filename: 'bundle.js'
    }
};

the loaders property should be inside the module property

@RubenCordeiro
Copy link

@Couto You are right, the configuration was wrong, it's working fine now. Thanks for taking the time to help me.

@pkosenko 's issue may be related to misconfiguration as well.

@pkosenko
Copy link
Author

Yes, thanks. Being new to webpack, I actually trusted the webpack documentation. When I used "module.loaders:" as specified, I got an error, so I removed "module." But apparently it needs to be "module: {loaders: [] }". Maybe webpack needs a better example?

https://webpack.github.io/docs/configuration.html

So . . . when webpack could not load babelify 6.1 locally, it reverted to my babel 5.8 global installation?

@joshburgess
Copy link

joshburgess commented May 20, 2016

I am having the same issue without having the config syntax wrong. Works fine in Node 5.11 but chokes on JSX in Node 6.0+.... #webpack/webpack#2462

My .babelrc:

{
  "presets": ["es2015", "react", "stage-0"],
  "plugins": ["react-hot-loader/babel"]
}

A section from my webpack.config.dev.js:

const NODE_HOST = process.env.NODE_HOST || '0.0.0.0';
const NODE_PORT = process.env.NODE_PORT || 3000;

const config = {
  devtool: 'inline-source-map', // works (original)
  // devtool: 'cheap-source-map', // works (transformed)
  resolve: {
    root: path.join(__dirname, 'src'),
    extensions: ['', '.js', '.jsx', '.json', '.css', '.scss'],
  },
  entry: [
    'eventsource-polyfill',
    `webpack-hot-middleware/client?http://${NODE_HOST}:${NODE_PORT}`,
    'react-hot-loader/patch',
    './src/index',
  ],
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'js/bundle.js',
    publicPath: '/static/',
  },
  plugins: [
    new webpack.DefinePlugin({
      process: {
        env: {
          NODE_ENV: JSON.stringify('development'),
        },
      },
    }),
    new ExtractTextPlugin('css/bundle.css', {
      allChunks: true,
    }),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin(),
  ],
  module: {
    loaders: [
      {
        test: /\.js$/,
        loaders: ['source-map', 'babel'],
        include: [
          path.join(__dirname, 'src'),
        ],
        exclude: [
          path.join(__dirname, 'src', 'assets'),
        ],
      },
      {
        test: /\.css$/,
        loader: ExtractTextPlugin.extract('style', 'css'),
        include: [
          path.join(__dirname, 'src', 'assets', 'css'),
          path.join(__dirname, 'node_modules'),
        ],
      },
      {
        test: /\.scss$/,
        loader: ExtractTextPlugin.extract('style', 'css!sass'),
        include: [
          path.join(__dirname, 'src', 'assets', 'scss'),
        ],
      },
      {
        // test: /\.(woff2|woff|ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        test: /\.(woff2|woff|ttf|eot|svg)(\?.*$|$)/,
        loader: 'file-loader?name=fonts/[name].[ext]',
        include: [
          path.join(__dirname, 'src'),
          path.join(__dirname, 'node_modules'),
        ],
      },
      {
        // test: /\.(jpg|jpeg|gif|png|ico)$/,
        test: /\.(jpg|jpeg|gif|png|ico)(\?.*$|$)$/,
        loader: 'file-loader?name=img/[name].[ext]',
        include: [
          path.join(__dirname, 'src'),
          path.join(__dirname, 'node_modules'),
        ],
      },
    ],
  },
};

@TannerPerrien
Copy link

Leaving a note here in case someone has the same issue as me. Babel's docs show the webpack setup as such:

module: {
  loaders: [
    {
      test: /\.js$/,
      exclude: /node_modules/,
      loader: "babel-loader"
    }
  ]
}

And this is fine as long as your jsx code is in file with a .js extension. It is recommended to use the .jsx file extension, but if you do this without updating the webpack config, webpack will not use the babel loader to process the .jsx files.

You can easily fix by updating your config to process both .js and .jsx files:

module: {
  loaders: [
    {
      test: /\.(js|jsx)$/,
      exclude: /node_modules/,
      loader: "babel-loader"
    }
  ]
}

@brhx
Copy link

brhx commented Jul 24, 2016

Oh my goodness I've spent the last two hours debugging that. Thank you so much @TannerPerrien!

@joshwiens
Copy link
Contributor

Resolving this as the issue contains a resolution to the reported problem

@williambryan777
Copy link

this can solve this problem.
.babelrc configuration:

{
    "presets": [
        "react",
        "es2015",
        "stage-0"
    ],
    // "plugins": [
    //     "transform-class-properties"
    // ]
    "plugins": [
        "react-hot-loader/babel"
        // "transform-class-properties",
        // "transform-react-constant-elements",
        // "transform-react-remove-prop-types",
        // "transform-react-inline-elements"
    ]
}

and webpack.config.js loaders section:

 loaders: [{
            test: /\.js|.jsx?$/,
            exclude: /(node_modules)/,
            loaders: ["babel-loader"]
        }

the devDependencies section of package.json confguration:

"devDependencies": {
    "babel-cli": "^6.9.0",
    "babel-core": "^6.10.4",
    "babel-eslint": "^6.0.4",
    "babel-loader": "^6.2.5",
    "babel-plugin-react-transform": "^2.0.2",
    "babel-plugin-rewire": "^1.0.0-rc-3",
    "babel-plugin-transform-class-properties": "^6.11.5",
    "babel-plugin-transform-react-constant-elements": "^6.8.0",
    "babel-plugin-transform-react-inline-elements": "^6.8.0",
    "babel-plugin-transform-react-remove-prop-types": "^0.2.7",
    "babel-plugin-transform-runtime": "^6.9.0",
    "babel-preset-es2015": "^6.9.0",
    "babel-preset-node5": "^11.1.0",
    "babel-preset-react": "^6.5.0",
    "babel-preset-stage-0": "^6.5.0",
    "babel-register": "^6.9.0",
    "babel-template": "^6.9.0",
    "babel-types": "^6.9.0",
    "css-loader": "^0.25.0",
    "react-hot-loader": "^3.0.0-beta.3",
    "style-loader": "^0.13.1"
  }

@yeeking
Copy link

yeeking commented Oct 20, 2016

Minimal stuff I had to do to get an es6 react -> babel -> webpack build chain working

npm install --save-dev babel babel-cli babel-core babel-loader babel-preset-es2015 babel-preset-react webpack

Added this to package.json

  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "webpack": "webpack --config config/webpack.js"
  },
   "babel": {
    "presets": [
      "es2015",
      "react"
    ]
  }

This is what ended up in my devDependencies section in package.json:

  "devDependencies": {
    "babel": "^6.5.2",
    "babel-cli": "^6.16.0",
    "babel-core": "^6.17.0",
    "babel-loader": "^6.2.5",
    "babel-preset-es2015": "^6.16.0",
    "babel-preset-react": "^6.16.0",
    "webpack": "^1.13.2"
  },

config/webpack.js has this:

var path = require('path');

module.exports = {
  entry: path.resolve(__dirname, '../src/client/scripts/client.js'),
  output: {
    path: path.resolve(__dirname, '../dist'),
    filename: 'bundle.js'
  },
  module: {
    loaders: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        loader: "babel-loader"
      }
    ]
  }
};

@geraldchecka
Copy link

@TannerPerrien @sam3d Nice, In addition to that, you could also exclude bower_components in babel loader config like this.

loaders: [{
  test: /\.(js|jsx)$/,
  exclude: /(node_modules|bower_components)/,
  loader: "babel-loader"
}]

@rafallyczkowski
Copy link

Please help: #380

@Knighton910
Copy link

thanks @TannerPerrien

🎉 test: /\.(js|jsx)$/
Awesome

@DrYSG
Copy link

DrYSG commented May 30, 2017

I thought I had the solution from @TannerPerrien , it sounded great. But I am still stuck getting the JSX to load.

image

@Couto
Copy link
Member

Couto commented Jun 3, 2017

@DrYSG as far as I can see from your screenshot, you need to tell webpack to look for the .jsx if no extension is provided.

You can add the following snippet to the webpack configuration object.

resolve: { extensions: [".jsx", ".js", ".json"] }

https://webpack.js.org/configuration/resolve/#resolve-extensions

@DrYSG
Copy link

DrYSG commented Jun 5, 2017

Thanks, that might well have done it.

@shashankKeshava
Copy link

shashankKeshava commented Feb 1, 2018

I'm facing a similar error. Still not able to fix it

Error:

ERROR in ./src/index.js
Module parse failed: Unexpected token (6:12)
You may need an appropriate loader to handle this file type.
|     render() {
|         return (
|             <div>
|                 <h1>Welcome to React Boilerplate</h1>
|             </div>

Webpack Config:

'use strict';

const webpack = require('webpack');
const htmlWebpack = require('html-webpack-plugin');

const commonPaths = require('./common-paths');
console.log(commonPaths.srcPath);
module.exports = {
    // Entry: First file webpack starts(your dependency graph)
    entry: {
        app: commonPaths.inputPath,
    },
    // Output: How and where to put bundles and format them
    output: {
        filename: 'bundle.js',
        path: commonPaths.outputPath,
    },
    // Loaders:  How to treat files before adding to dependency graphs
    module: {
        loaders: [
            {
                test: /\.(js|jsx)$/,
                include: [commonPaths.inputPath],
                loader: ['babel-loader'],
                query: {
                    presets: ['es2015', 'react'],
                    plugins: ['transform-runtime'],
                },
                options: {
                    cacheDirectory: true,
                },
            },
        ],
        rules: [
            {
                test: /\.png$/,
                use: [
                    {
                        loader: 'url-loader',
                        options: {
                            limit: 1000,
                        },
                    },
                ],
            },
        ],
    },
    // Plugins: Extremely Customisable
    plugins: [new webpack.ProgressPlugin(), new htmlWebpack()],
};

The entire project is available at React-Redux-BoilerPlate

@loganfsmyth
Copy link
Member

Try moving your babel-loader stuff into rules.

@shashankKeshava
Copy link

@loganfsmyth rules does not support query parameter

Error:

/Users/shashank/webapps/react-redux-boilerplate/node_modules/webpack/lib/RuleSet.js:174
			throw new Error(RuleSet.buildErrorMessage(rule, new Error("options/query cannot be used with loaders (use options for each array item)")));
			^

Error: options/query cannot be used with loaders (use options for each array item) in {
  "test": {},
  "include": [
    "/Users/shashank/webapps/react-redux-boilerplate/src/index.js"
  ],
  "loader": [
    "babel-loader"
  ],
  "query": {
    "presets": [
      "es2015",
      "react"
    ],
    "plugins": [
      "transform-runtime"
    ]
  },
  "options": {
    "cacheDirectory": true
  }
}

@loganfsmyth
Copy link
Member

options is what you want, like where you have cacheDirectory.

@shashankKeshava
Copy link

@loganfsmyth I tried it but still facing the same error

@shashankKeshava
Copy link

Hi @loganfsmyth thanks for the help was able to fix the issue with

module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                include: [commonPaths.inputPath],
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: [['es2015', { modules: false }], 'react'],
                        plugins: ['transform-runtime'],
                        cacheDirectory: true,
                    },
                },
            },
            {
                test: /\.png$/,
                use: [
                    {
                        loader: 'url-loader',
                        options: {
                            limit: 1000,
                        },
                    },
                ],
            },
        ],
    }

@thujone
Copy link

thujone commented Apr 5, 2020

Had to dick around with the goddamn configuration for hours and hours to get this stupid shit to work. Configuration is supposed to help programmers, not eff up their day. Stupid-ass bullshit technology.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests