如何在服务器端渲染图像?

时间:2016-02-26 19:13:22

标签: javascript node.js image reactjs express

如何使用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 ..

1 个答案:

答案 0 :(得分:1)

您的服务器需要单独的webpack配置

  1. 安装此模块以排除node_modules:

    npm install --save webpack-node-externals 
    
  2. 为您的服务器创建单独的webpack配置:

    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'
          }
        ]
      }
    }
    
  3. 这是一个示例服务器webpack.config.js:

    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'
          }
        ]
      }
    }
    
  4. 如果使用上面的webpack.config.js示例,请运行webpack然后编译服务器文件:

    webpack
    node dist/bundle.js