未定义React

时间:2018-10-08 07:30:54

标签: reactjs express webpack server

我正在尝试在快递服务器上渲染我的React代码,下面是该代码

const express  =require('express');
const react  =require('react');
const renderToString  =require('react-dom/server').renderToString;
const HelloWorld=require('./client/components/Home');
const app = express();

app.get('/', (req, res) => {
    const content=renderToString(<HelloWorld/>);
    res.send(content);
});

app.listen(3000, () => {
  console.log('Listening on prot 3000');
});

webpack.server.js

 const path = require('path');

module.exports = {
  // Inform webpack that we're building a bundle
  // for nodeJS, rather than for the browser
  target: 'node',

  // Tell webpack the root file of our
  // server application
  entry: './src/index.js',

  // Tell webpack where to put the output file
  // that is generated
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'build'),

  },
  module:{
      rules:[
          {
              test:/\.js?$/,
              loader:'babel-loader',
              exclude:/node_modules/,
              options:{
                  presets:[
                      'react',
                      'stage-0',//asyc purpose,
                      ['env',{targets:{browsers:['last 2 versions']}}]
                  ]
            }
          }
      ]
  }
};

package.json

 "dev:build:server": "webpack --config webpack.server.js"

当我使用node build \ bundle.js运行我的应用程序时,即使我在index.js中导入react,我也没有定义react

1 个答案:

答案 0 :(得分:0)

更改

const react=require('react');

const React=require('react'); 解决了我的问题