I am trying to serve my React app on top of Node/Express after transpiling with Webpack. I've used create-react-app, but want learn to build from scratch so am new to using Node/Express/Webpack. After going through various tutorials, I am stuck trying to render React elements after transpiling with Webpack (Only HTML is being served).
I also run the following commands to create my bundle.js file and navigate to localhost:3000
-npm run 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>
My webpack.config.js is currently...
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()
]
}
My server.js file is as follows...
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)
})
And my App.js only contains the follow React elements:
import React, { Component } from 'react'
class App extends Component {
render() {
return (
<div>
<h1>This is the main App</h1>
</div>
)
}
}
export default App
Also, my 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"
}
}
via jamesvphan
No comments:
Post a Comment