Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Extract the Hapi Server to expose it for testing #277

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 1 addition & 4 deletions .babelrc
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
{
"presets": ['react', 'es2015', 'stage-0'],
"plugins": [
'transform-object-rest-spread'
]
"presets": ['react', 'es2015', 'stage-0']
}
156 changes: 156 additions & 0 deletions lib/utils/dev-server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
import Hapi from 'hapi'
import Boom from 'boom'
import React from 'react'
import ReactDOMServer from 'react-dom/server'
import webpack from 'webpack'
import Negotiator from 'negotiator'
import parsePath from 'parse-filepath'
import find from 'lodash/find'
import webpackRequire from 'webpack-require'
import WebpackPlugin from 'hapi-webpack-plugin'
import fs from 'fs'
import glob from 'glob'
import webpackConfig from './webpack.config'
const debug = require('debug')('gatsby:application')

module.exports = function devServer (program, pages, callback) {
const { directory } = program
const compilerConfig = webpackConfig(program, directory, 'develop', program.port)

const compiler = webpack(compilerConfig.resolve())

let HTMLPath = `${directory}/html`
// Check if we can't find an html component in root of site.
if (glob.sync(`${HTMLPath}.*`).length === 0) {
HTMLPath = '../isomorphic/html'
}

const htmlCompilerConfig = webpackConfig(program, directory, 'develop', program.port)

webpackRequire(htmlCompilerConfig.resolve(), require.resolve(HTMLPath), (error, factory) => {
if (error) {
console.log(`Failed to require ${directory}/html.js`)
error.forEach((e) => {
console.log(e)
})
process.exit()
}
const HTML = factory()
debug('Configuring develop server')

// Setup and start Hapi to serve html + static files + webpack-hot-middleware.
const server = new Hapi.Server()
server.connection({
host: program.host,
port: program.port,
})

server.route({
method: 'GET',
path: '/html/{path*}',
handler: (request, reply) => {
if (request.path === 'favicon.ico') {
return reply(Boom.notFound())
}

try {
const htmlElement = React.createElement(
HTML, {
body: '',
}
)
let html = ReactDOMServer.renderToStaticMarkup(htmlElement)
html = `<!DOCTYPE html>\n${html}`
return reply(html)
} catch (e) {
console.log(e.stack)
throw e
}
},
})

server.route({
method: 'GET',
path: '/{path*}',
handler: {
directory: {
path: `${directory}/pages`,
listing: false,
index: false,
},
},
})

server.ext('onRequest', (request, reply) => {
const negotiator = new Negotiator(request.raw.req)

// Try to map the url path to match an actual path of a file on disk.
const parsed = parsePath(request.path)
const page = find(pages, (p) => p.path === (`${parsed.dirname}/`))

let absolutePath = `${directory}/pages`
let path
if (page) {
path = `/${parsePath(page.requirePath).dirname}/${parsed.basename}`
absolutePath += `/${parsePath(page.requirePath).dirname}/${parsed.basename}`
} else {
path = request.path
absolutePath += request.path
}
let isFile = false
try {
isFile = fs.lstatSync(absolutePath).isFile()
} catch (e) {
// Ignore.
}

// If the path matches a file, return that.
if (isFile) {
request.setUrl(path)
reply.continue()
// Let people load the bundle.js directly.
} else if (request.path === '/bundle.js') {
reply.continue()
} else if (negotiator.mediaType() === 'text/html') {
request.setUrl(`/html${request.path}`)
reply.continue()
} else {
reply.continue()
}
})

const assets = {
noInfo: true,
reload: true,
publicPath: compilerConfig._config.output.publicPath,
}
const hot = {
hot: true,
quiet: true,
noInfo: true,
host: program.host,
headers: {
'Access-Control-Allow-Origin': '*',
},
stats: {
colors: true,
},
}

server.register({
register: WebpackPlugin,
options: {
compiler,
assets,
hot,
},
}, (er) => {
if (er) {
console.log(er)
process.exit()
}

callback(server)
})
})
}
179 changes: 9 additions & 170 deletions lib/utils/develop.js
Original file line number Diff line number Diff line change
@@ -1,184 +1,23 @@
require('node-cjsx').transform()
import Hapi from 'hapi'
import Boom from 'boom'
import React from 'react'
import ReactDOMServer from 'react-dom/server'
import webpack from 'webpack'
import Negotiator from 'negotiator'
import parsePath from 'parse-filepath'
import find from 'lodash/find'
import webpackRequire from 'webpack-require'
import WebpackPlugin from 'hapi-webpack-plugin'
import opn from 'opn'
import fs from 'fs'
import glob from 'glob'

import globPages from './glob-pages'
import webpackConfig from './webpack.config'
const debug = require('debug')('gatsby:application')
import devServer from './dev-server'

module.exports = (program) => {
const directory = program.directory

// Load pages for the site.
return globPages(directory, (err, pages) => {
const compilerConfig = webpackConfig(program, directory, 'develop', program.port)

const compiler = webpack(compilerConfig.resolve())

let HTMLPath = `${directory}/html`
// Check if we can't find an html component in root of site.
if (glob.sync(`${HTMLPath}.*`).length === 0) {
HTMLPath = '../isomorphic/html'
}

const htmlCompilerConfig = webpackConfig(program, directory, 'develop', program.port)
// Remove react-transform option from Babel as redbox-react doesn't work
// on the server.
htmlCompilerConfig.removeLoader('js')
htmlCompilerConfig.loader('js', {
test: /\.jsx?$/, // Accept either .js or .jsx files.
exclude: /(node_modules|bower_components)/,
loader: 'babel',
query: {
presets: ['react', 'es2015', 'stage-1'],
plugins: ['add-module-exports'],
},
})

webpackRequire(htmlCompilerConfig.resolve(), require.resolve(HTMLPath), (error, factory) => {
if (error) {
console.log(`Failed to require ${directory}/html.js`)
error.forEach((e) => {
return globPages(directory, (err, pages) =>
devServer(program, pages, server => {
server.start((e) => {
if (e) {
console.log(e)
})
process.exit()
}
const HTML = factory()
debug('Configuring develop server')

// Setup and start Hapi to serve html + static files + webpack-hot-middleware.
const server = new Hapi.Server()
server.connection({
host: program.host,
port: program.port,
})

server.route({
method: 'GET',
path: '/html/{path*}',
handler: (request, reply) => {
if (request.path === 'favicon.ico') {
return reply(Boom.notFound())
}

try {
const htmlElement = React.createElement(
HTML, {
body: '',
}
)
let html = ReactDOMServer.renderToStaticMarkup(htmlElement)
html = `<!DOCTYPE html>\n${html}`
return reply(html)
} catch (e) {
console.log(e.stack)
throw e
}
},
})

server.route({
method: 'GET',
path: '/{path*}',
handler: {
directory: {
path: `${directory}/pages`,
listing: false,
index: false,
},
},
})

server.ext('onRequest', (request, reply) => {
const negotiator = new Negotiator(request.raw.req)

// Try to map the url path to match an actual path of a file on disk.
const parsed = parsePath(request.path)
const page = find(pages, (p) => p.path === (`${parsed.dirname}/`))

let absolutePath = `${directory}/pages`
let path
if (page) {
path = `/${parsePath(page.requirePath).dirname}/${parsed.basename}`
absolutePath += `/${parsePath(page.requirePath).dirname}/${parsed.basename}`
} else {
path = request.path
absolutePath += request.path
}
let isFile = false
try {
isFile = fs.lstatSync(absolutePath).isFile()
} catch (e) {
// Ignore.
}

// If the path matches a file, return that.
if (isFile) {
request.setUrl(path)
reply.continue()
// Let people load the bundle.js directly.
} else if (request.path === '/bundle.js') {
reply.continue()
} else if (negotiator.mediaType() === 'text/html') {
request.setUrl(`/html${request.path}`)
reply.continue()
} else {
reply.continue()
if (program.open) {
opn(server.info.uri)
}
})

const assets = {
noInfo: true,
reload: true,
publicPath: compilerConfig._config.output.publicPath,
}
const hot = {
hot: true,
quiet: true,
noInfo: true,
host: program.host,
headers: {
'Access-Control-Allow-Origin': '*',
},
stats: {
colors: true,
},
}

server.register({
register: WebpackPlugin,
options: {
compiler,
assets,
hot,
},
}, (er) => {
if (er) {
console.log(er)
process.exit()
}

server.start((e) => {
if (e) {
console.log(e)
}
if (program.open) {
opn(server.info.uri)
}
return console.log('Listening at:', server.info.uri)
})
console.log('Listening at:', server.info.uri)
})
})
})
)
}
21 changes: 18 additions & 3 deletions lib/utils/webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,14 @@ module.exports = (program, directory, stage, webpackPort = 1500, routes = []) =>
exclude: /(node_modules|bower_components)/,
loader: 'babel',
query: {
plugins: ['add-module-exports'],
presets: [
'babel-preset-react',
'babel-preset-es2015',
'babel-preset-stage-0',
].map(require.resolve),
plugins: [
'babel-plugin-add-module-exports',
].map(require.resolve),
},
})
config.loader('coffee', {
Expand Down Expand Up @@ -260,10 +267,18 @@ module.exports = (program, directory, stage, webpackPort = 1500, routes = []) =>
exclude: /(node_modules|bower_components)/,
loader: 'babel',
query: {
presets: ['react-hmre', 'react', 'es2015', 'stage-1'],
plugins: ['add-module-exports'],
presets: [
'babel-preset-react-hmre',
'babel-preset-react',
'babel-preset-es2015',
'babel-preset-stage-0',
].map(require.resolve),
plugins: [
'babel-plugin-add-module-exports',
].map(require.resolve),
},
})

return config

case 'static':
Expand Down
Loading