如何使用React在服务器端渲染图像和css文件?
这是我的服务器代码:
<ToggleButton Content="Toggle Button" Background="Transparent" BorderBrush="Transparent" BorderThickness="0" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" Canvas.Left="233" Canvas.Top="158">
<ToggleButton.ContentTemplate>
<DataTemplate>
<Button IsHitTestVisible="False" Content="{Binding}"/>
</DataTemplate>
</ToggleButton.ContentTemplate>
</ToggleButton>
主要组成部分:
const express = require('express')
const router = express.Router()
const ReactDOM = require('react-dom/server');
import Master from '../../../client/Master'
router.get('/', (req, res) => {
res.render('test.html', {reactOutput: ReactDOM.renderToString(<Master/>)});
});
但是当我用babel运行服务器时,我收到了这个错误:
/assets/img/logo.png:意外的角色&#39;?&#39; (1:0)
这是试图要求徽标的Header组件。
import React from "react";
import Intro from "./pages/Intro";
import Footer from "./components/Footer";
import Header from "./components/Header";
export default class Master extends React.Component {
constructor() {
super();
this.state = {appStatus: 'INTRO'}
}
render() {
let layout;
switch (this.state.appStatus) {
case "INTRO":
layout = <Intro/>;
}
return (
<div>
<Header/>
{layout}
<Footer/>
</div>
)
}
}
但它适用于客户端的webpack ..
答案 0 :(得分:1)
npm install --save webpack-node-externals
module.exports = {
const path = require('path')
const nodeExternals = require('webpack-node-externals')
context: path.resolve(__dirname, 'directory of your server file'),
entry: ['./filename of your server file'],
output: {
path: path.join(__dirname, 'directory of your bundled file'),
filename: 'filename of your bundled file'
},
target: 'node',
externals: [nodeExternals()],
module: {
rules: [
{
test: /\.(jpe?g|png|gif|svg|ico)$/i,
use: 'url-loader?limit=8192'
}
]
}
}
module.exports = {
const path = require('path')
const nodeExternals = require('webpack-node-externals')
context: path.resolve(__dirname, 'src'),
entry: ['./index.js'],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js'
},
target: 'node',
externals: [nodeExternals()],
module: {
rules: [
{
test: /\.(jpe?g|png|gif|svg|ico)$/i,
use: 'url-loader?limit=8192'
}
]
}
}
webpack
node dist/bundle.js