Search code examples
reactjswebpackjsxcreate-react-app

Create-React-App build - "Uncaught SyntaxError: Unexpected token <"


I realize this question has been asked multiple times but nothing has worked for me...

I'm trying to create a static build of a create-react-app project but I'm getting the following errors:

Uncaught SyntaxError: Unexpected token <     1.ca81c833.chunk.js:1
Uncaught SyntaxError: Unexpected token <     main.7ced8661.chunk.js:1

Due to these files being minified, I'm not sure where to begin in debugging them.

Per other SO responses, here are some things I've tried:

//Original index.html file, which gets included in the built file:
<script type="text/babel" src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.min.js"></script>

//package.json
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",

//.babelrc file
{
  "presets": ["react", "es2015", "stage-1"]
}

Not sure if this is relevant, but I have this on my express server, which I believe is standard:

if (process.env.NODE_ENV === "production") {

    app.use(express.static('client/built'));
    app.get("*", (req, res) => {
        res.sendFile(require('path')
            .resolve(__dirname, 'client', 'build', 'index.html'));
    })
}

Assuming it's actually a JSX issue, the whole thing is very confusing - shouldn't create-react-app be handling JSX automatically?

UPDATE: I just posted this question but already have a relevant update. I'm able to serve the page statically through pm2 by running pm2 serve build so I think the issue may be with my server configuration.


Solution

  • I ended up finding an answer here: https://github.com/facebook/create-react-app/issues/1812

    I trimmed down the full solution from above, but I changed:

    app.use(express.static('client/build'));
    app.get("*", (req, res) => {
        res.sendFile(require('path')
            .resolve(__dirname, 'client', 'build', 'index.html'));
    })
    

    to:

    const root = require('path').join(__dirname, 'client', 'build')
    app.use(express.static(root));
    app.get("*", (req, res) => {
        res.sendFile('index.html', { root });
    })
    

    It's definitely a bit strange to me that the first block didn't work. I assume it has something to do with the relative links in my React project since I do get an index.html file delivered to browser, despite getting the error. Maybe a completely static file would work with the first block, but I'd be interested to know if that's accurate.