我的server.js
是:
var path = require('path');
var express = require('express');
var app = express();
var PORT = process.env.PORT || 8080;
var React = require('react');
var ReactDOMServer = require('react-dom/server');
var companyComponent = require('./src/components/company');
// using webpack-dev-server and middleware in development environment
if(process.env.NODE_ENV !== 'production') {
var webpackDevMiddleware = require('webpack-dev-middleware');
var webpackHotMiddleware = require('webpack-hot-middleware');
var webpack = require('webpack');
var config = require('./webpack.config');
var compiler = webpack(config);
app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath }));
app.use(webpackHotMiddleware(compiler));
}
app.use(express.static(path.join(__dirname, 'dist')));
app.use(handleRender);
function handleRender(req, res) {
res.send(renderFullPage());
}
function renderFullPage() {
var html = ReactDOMServer.renderToString(companyComponent());
console.log(html);
return `
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Run The Call</title>
<link href="https://fonts.googleapis.com/css?family=Roboto:400,100,100italic,300,300italic,400italic,500,500italic,700,700italic,900,900italic" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css" media="screen" title="no title" charset="utf-8">
</head>
<body>
<div id='root'/>
</body>
<script src="/bundle.js"></script>
</html>
`
}
app.listen(PORT, function(error) {
if (error) {
console.error(error);
} else {
console.info("Listening on port %s", PORT);
}
});
我的companyComponent
使用ES6:
import React, { Component } from 'react';
const companyHero = require('../assets/images/company.jpg');
import Footer from './footerComponent'
import Navbar from './navbarComponent';
class Company extends React.Component {
render() {
let heroStyle = {backgroundImage: 'url(' + companyHero + ')'};
return (
<div className="wrapper company-page">
<Navbar type={"transparent"}/>
<div className="jumbotron" style={heroStyle}>
<div className="container-fluid">
<div className="row">
<div className="col-md-6 col-md-offset-3 text-center">
<h1>ABOUT THE COMPANY</h1>
</div>
</div>
</div>
</div>
<Footer />
</div>
)
}
}
export default Company;
当我尝试使用babel-node server.js
运行它时,我得到:
/Users/myuser/n/lib/node_modules/babel-cli/node_modules/babel-core/lib/transformation/file/index.js:614
throw err;
^
SyntaxError: /Users/myuser/rtc/src/assets/images/icons/facebook.png: Unexpected characte
r '�' (1:0)
> 1 | �PNG
| ^
2 |
3 |
我做错了什么?
答案 0 :(得分:3)
您正在尝试加载节点(和babel)不理解的文件facebook.png
。执行require('someFile')
时,将评估文件中的JavaScript。因此,babel / node正在尝试将PNG图像评估为JavaScript文件。
您有两个选项,您可以执行const companyHero = '../assets/images/facebook.png'
或者您可以阅读文件fs.readFileSync('../assets/images/facebook.png')
,然后将backgroundImage
属性设置为图像数据的base64数据。
前者可能是更好的选择,因为您正在渲染文件服务器端,并且不希望在页面加载之前加载公司徽标。