[英]Webpack 2 targeting node doesn't compile JSX
我正在用React構建一個Universal JS應用程序,我正在使用webpack 2捆綁我的服務器端代碼。
在構建服務器端代碼時,似乎webpack沒有轉換JSX,因為我收到以下錯誤:
我做了一個repo來重現錯誤 。 克隆它,點擊npm install ,然后在終端上運行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);
})
}
你告訴Webpack將.jsx
文件傳遞給Babel加載器:
test: /\.jsx$/,
loader: 'babel',
但是,您的JSX包含在.js
文件中,如server/router.js
,因此您應該擴展測試以匹配.js
和.jsx
:
test: /\.jsx?$/
此外,您必須從Babel加載程序配置中刪除include
屬性,因為這意味着加載程序應處理的文件必須存在於./shared
目錄中,而./server/router.js
則不存在。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.