刚开始使用redux,卡在一个奇怪的情况下,webpack显示没有错误,但在html中,组件没有得到渲染。文件结构:
dist
bundle.js
node_modules
src
index.js
.babelrc
index.html
package.json
server.js
webpack.config.js
的index.html
<html>
<head>
<title>jie blog</title>
<meta charset="utf-8">
</head>
<body>
<div id="root"></div>
</body>
<script src="dist/bundle.js">
</script>
</html>
index.js
import React from 'react'
import ReactDOM from 'react-dom'
import { Provider } from 'react-redux'
import { Router, Route, Redirect, browserHistory } from 'react-router'
import { syncHistoryWithStore } from 'react-router-redux'
class App extends React.Component{
render(){
return(
<div>
hello world
</div>
)
}
}
ReactDOM.render(
<App/>,
document.getElementById('root')
)
server.js
var http = require('http')
var express = require('express')
var httpProxy = require('http-proxy')
var fs = require('fs')
var babelrc = fs.readFileSync('./.babelrc')
var config = JSON.parse(babelrc)
require('babel-core/register')(config)
var proxy = httpProxy.createProxyServer({})
var app = express()
app.use(require('morgan')('short'))
// webpack
var webpack = require('webpack')
var config = require('./webpack.config')
var compiler = webpack(config)
app.use(require('webpack-dev-middleware')(compiler, {
noInfo: true,
publicPath: config.output.publicPath
}))
app.use(require('webpack-hot-middleware')(compiler))
app.all(/^\/api\/(.*)/, function api(req, res){
proxy.web(req, res, {
target: 'http://localhost:5000'
})
})
app.get(/.*/, function root(req, res){
res.sendFile(__dirname + '/index.html')
})
const server = http.createServer(app)
server.listen(process.env.PORT || 3000, function(){
const address = server.address()
console.log('listening on %j', address)
})
webpack.config.js
const webpack = require('webpack')
const path = require('path')
module.exports = {
devtool: 'source-map',
entry: [
'webpack-hot-middleware/client',
path.resolve(__dirname, 'src/index.js')
],
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/'
},
resolve: {
extensions: ['', '.jsx', '.js', '.json', '.scss']
},
module: {
loaders: [
{
test: /\.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['es2015', 'react']
}
}
]
}
}
输出html
<body>
<div id="root"></div>
<script src="dist/bundle.js">
</script>
</body>
答案 0 :(得分:1)
看起来它不是ReactDOM的问题,而是配置问题。
在server.js
中...
app.use(require('webpack-dev-middleware')(compiler, {
noInfo: true,
publicPath: config.output.publicPath // <--- /static/
}))
...
publicPath
指定在浏览器中引用时bundle.js的公共URL地址。所以你在webpack.config.js中设置了/static/bundle.js。好的!
因此Index.html需要请求/static/bundle.js。和不 dist / bundle.js
...
<script src="static/bundle.js"></script>
...
当index.html在/dist
和webpack-dev-middleware
处理请求时,/static
处理了请求,返回了index.html文件,而不是您的bundle.js
app.get(/.*/, function root(req, res){
res.sendFile(__dirname + '/index.html')
})
这就是你Uncaught SyntaxError: Unexpected token < bundler.js:1
的原因。
答案 1 :(得分:0)
问题是Babel只转换.jsx文件:
test: /\.jsx?$/,
而使用JSX的文件扩展名为.js(index.js)