Abraham Hurtado Abraham Hurtado - 1 year ago 209
Node.js Question

Webpack 2 targeting node doesn't compile JSX

I'm building a Universal JS app with React and I'm using webpack 2 to bundle my server side code.

When building the server side code, it seems that webpack isn't transpiling JSX because I'm getting the following error:

I made a repo to reproduce the error. Clone it, hit npm install and then npm run build:backend on the terminal

ERROR in ./server/router.js
Module parse failed: webpack-target-node\server\router.js Unexpected token (8:31)
You may need an appropriate loader to handle this file type.
| export default (req, res) => {
| match({ routes, location: req.url }, (err, redirect, props) => {
| const app = renderToString(<RouterContext {...props} />);
| const html = `
@ ./server.js 3:0-46


const webpack = require('webpack');
const { resolve } = require('path');
const nodeExternals = require('webpack-node-externals');

module.exports = () => {
return {
target: 'node',
entry: './server.js',
output: {
path: resolve(__dirname, 'serverBuild'),
filename: 'server.js'
resolve: {
extensions: [ '', '.js' ]
externals: [ nodeExternals() ],
module: {
loaders: [
test: /\.jsx$/,
loader: 'babel',
query: {
presets: [ 'react', 'stage-0' ]
exclude: /node_modules/,
include: resolve('./shared')


import express from 'express';

import routeMiddleware from './server/router';

const app = express();

app.use('/', express.static(`${__dirname}/build`));


app.listen(3000, () => {
console.log('Node server is running on http://localhost:3000');


import React from 'react';
import { renderToString } from 'react-dom/server';
import { match, RouterContext } from 'react-router';
import router from '../shared/routes'

export default (req, res) => {
match({ routes, location: req.url }, (err, redirect, props) => {
// here is where the building process fails
const app = renderToString(<RouterContext {...props} />);

const html = `
<html lang="en">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="css/style.css" rel="stylesheet">
<div id="react-app">${app}</div>
<script type="text/javascript" src="/bundle.js"></script>


Answer Source

You're telling Webpack to pass .jsx files to the Babel loader:

test: /\.jsx$/,
loader: 'babel',

However, your JSX is contained within .js files, like server/router.js, so you should expand the test to match both .js and .jsx:

test: /\.jsx?$/

Also, you have to remove the include property from the Babel loader configuration, because it means that the files that should be processed by the loader must exist in the ./shared directory, and ./server/router.js doesn't.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download