reactjsgruntjsbabeljsbrowserifybabelify

browserify fails to parse jsx despite using babel-preset-react, babel-preset-es2015 and babel-preset-stage-3


I am using grunt to automate the whole process. This is what my configuration looks like:

browserify: {
        dist: {
            files: {
                '<%= dirs.dest %>/index.js': [
                    '<%= dirs.src %>/index.js'
                ]
            },
            options: {
                transform: [
                    ['babelify', { presets: ['es2015', 'stage-3', 'react'] }]
                ]
            },
        }
    },

It fails when attempting to parse one of the react components that are imported with the following error:

>>             <div>
>>             ^
>> ParseError: Unexpected token
Warning: Error running grunt-browserify. Use --force to continue.

Aborted due to warnings.

I've tried using the same file that throws the error with babel-standalone in the browser and it works just fine.

I'm stumped as to how to fix this as most links say that using babel-preset-react should fix it (and it works with another project that I have)


Solution

  • By default, browserify does not transpile included files that are outside your project. Since the component that was causing the issue was being included from node_modules, I had to configure its package.json file to ensure that browserify knew that its source was not transpiled and that it had to transpile it when it was being included.

    I was able to do that by including this in my node_modules component's package.json:

    "browserify": { "transform": [ "babelify" ] }
    

    Once I added this and ensured that the component was being exported from the module, everything started working as expected.

    Reference: https://github.com/babel/babel/issues/1625#issuecomment-105334250