我正在使用React构建一个Universal JS应用程序,我正在使用webpack 2捆绑我的服务器端代码。
在构建服务器端代码时,似乎webpack没有转换JSX,因为我收到以下错误:
I made a repo to reproduce the error。克隆它,点击 npm install ,然后在终端上 npm run build:backend
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
webpack.config.node.js
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')
}
]
}
}
}
server.js
import express from 'express';
import routeMiddleware from './server/router';
const app = express();
app.use('/', express.static(`${__dirname}/build`));
app.use(routeMiddleware);
app.listen(3000, () => {
console.log('Node server is running on http://localhost:3000');
});
服务器/ router.js
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">
<head>
<title></title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="css/style.css" rel="stylesheet">
</head>
<body>
<div id="react-app">${app}</div>
<script type="text/javascript" src="/bundle.js"></script>
</body>
</html>`;
res.send(html);
})
}
答案 0 :(得分:1)
您告诉Webpack将.jsx
个文件传递给Babel加载程序:
test: /\.jsx$/,
loader: 'babel',
但是,您的JSX包含在.js
文件中,例如server/router.js
,因此您应该扩展测试以匹配.js
和.jsx
:
test: /\.jsx?$/
此外,您必须从Babel加载程序配置中删除include
属性,因为这意味着加载程序应处理的文件必须存在于{{1}中}目录,./shared
没有。