Skip to content

Instantly share code, notes, and snippets.

@Raidus
Created October 26, 2017 00:12
Show Gist options
  • Save Raidus/142ff21d1bf8c2a67c26312cca66b399 to your computer and use it in GitHub Desktop.
Save Raidus/142ff21d1bf8c2a67c26312cca66b399 to your computer and use it in GitHub Desktop.
Render to Static Markup to a File with React
var fse = require('fs-extra')
var React = require('react')
var ReactDOMServer = require('react-dom/server')
var webpackRequire = require('webpack-require')
var webpackConfig = require('./webpack.config.js')
var template = require('./template.js')
webpackRequire(webpackConfig, template, function (error, factory) {
if (error) { console.error(error) }
var templateComponent = factory()
var html = ReactDOMServer.renderToStaticMarkup(React.createElement(templateComponent, {
title: 'Homepage',
body_content: 'Hello World!'
}))
fse.outputFileSync('./index.html', '<!doctype html>' + html)
})
import React from 'react'
class Template extends React.Component {
constructor (props) {
super(props)
}
render () {
const title = this.props.title
const body_content = this.props.body_content
return (
<html lang='en'>
<head>
<meta charSet='utf-8' />
<meta name='viewport' content='width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1'/>
<link rel='stylesheet' href='style.css' />
<title>{title}</title>
</head>
<body>
<div id='app' dangerouslySetInnerHTML={{__html: body_content}} />
<script src='main.js'></script>
</body>
</html>
)
}
}
Template.propTypes = {
title: React.PropTypes.string,
body_content: React.PropTypes.string
}
Template.defaultProps = {
title: 'no title supplied',
body_content: 'no content supplied'
}
export default Template
@lucasbarrosomk6
Copy link

could you include your webpack config file? I am getting the unexpected token '<' error

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment