在使用Webpack进行转换后,在Node / Express上运行的React App无法呈现。

时间:2017-05-26 16:45:46

标签: node.js reactjs express webpack

我试图在使用Webpack进行转换后,在Node / Express上提供我的React应用程序。我已经使用了create-react-app,但是想学习从头开始构建,所以我很擅长使用Node / Express / Webpack。经过各种教程之后,我在使用Webpack进行转换后尝试渲染React元素(仅提供HTML)。

我还运行以下命令来创建我的bundle.js文件并导航到localhost:3000

-npm运行webpack

-node server.js

<!doctype html>
<html lang="en">
  <head>
    <title>React App</title>
  </head>
  <body>
    <div id="root"></div>
    <h1>This is from the HTML file</h1>
    <script scr="bundle.js"></script>
  </body>
</html>

我的webpack.config.js目前正在......

var webpack = require('webpack')
var path = require('path') 

module.exports = {
  entry: [
    './src'
  ],
  output: {
    path: path.join(__dirname, 'public'),
    filename: 'bundle.js'
  },
  module: { 
    loaders: [{
      test: /\.js$/,
      exclude: /node_modules/,
      loader: 'babel-loader',
      query: { 
        presets: ['react', 'es2015']
      }
    }]
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoEmitOnErrorsPlugin()
  ]
}

我的server.js文件如下......

var express = require('express')
var path = require('path')
var fs = require('fs')

var app = express()

var PORT = process.env.PORT || 3000

app.set('view engine', 'html')

app.engine('html', function(path, options, callbacks) {
  fs.readFile(path, 'utf-B', callback)
})

app.use(express.static(path.join(__dirname, 'public')))

app.get('*', function(req, res) {
  res.sendFile(path.join(__dirname, 'public'), 'index.html')
})

app.use(function (err, req, res, next) {
  res.status(err.status || 500)
})

app.listen(PORT, function() {
  console.log('Server running on localhost:' + PORT)
})

我的App.js只包含以下React元素:

import React, { Component } from 'react'

class App extends Component {

  render() {
    return (
      <div>
        <h1>This is the main App</h1>
      </div>
    )
  }
}

export default App

另外,我的package.json

{
  "name": "poke-mean",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "NODE_PATH=$NODE_PATH:./src node server",
    "dev": "npm start & webpack-dev-server --progress --colors",
    "webpack": "webpack"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.15.3",
    "react": "^15.5.4",
    "react-dom": "^15.5.4",
    "react-router-dom": "^4.1.1"
  },
  "devDependencies": {
    "babel-core": "^6.24.1",
    "babel-loader": "^7.0.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "webpack": "^2.6.1",
    "webpack-dev-server": "^2.4.5"
  }
}

0 个答案:

没有答案