Use CommonJS for server modules

This commit is contained in:
Michael Jackson 2017-03-24 17:35:30 -07:00
parent c476954c99
commit 503b24e8d0
8 changed files with 84 additions and 55 deletions

View File

@ -1,4 +1,4 @@
export default [ module.exports = [
'goodjsproject', 'goodjsproject',
'thisoneisevil' 'thisoneisevil'
] ]

View File

@ -1,6 +1,6 @@
import fs from 'fs' const fs = require('fs')
import invariant from 'invariant' const invariant = require('invariant')
import webpack from 'webpack' const webpack = require('webpack')
const createBundle = (webpackStats) => { const createBundle = (webpackStats) => {
const { publicPath, assetsByChunkName } = webpackStats const { publicPath, assetsByChunkName } = webpackStats
@ -35,7 +35,7 @@ const createBundle = (webpackStats) => {
* An express middleware that sets req.manifest from the build manifest * An express middleware that sets req.manifest from the build manifest
* in the given file. Should be used in production to get consistent hashes. * in the given file. Should be used in production to get consistent hashes.
*/ */
export const assetsManifest = (webpackManifestFile) => { const assetsManifest = (webpackManifestFile) => {
let manifest let manifest
try { try {
manifest = JSON.parse(fs.readFileSync(webpackManifestFile, 'utf8')) manifest = JSON.parse(fs.readFileSync(webpackManifestFile, 'utf8'))
@ -58,7 +58,7 @@ export const assetsManifest = (webpackManifestFile) => {
* An express middleware that sets req.bundle from the build * An express middleware that sets req.bundle from the build
* info in the given stats file. Should be used in production. * info in the given stats file. Should be used in production.
*/ */
export const staticAssets = (webpackStatsFile) => { const staticAssets = (webpackStatsFile) => {
let stats let stats
try { try {
stats = JSON.parse(fs.readFileSync(webpackStatsFile, 'utf8')) stats = JSON.parse(fs.readFileSync(webpackStatsFile, 'utf8'))
@ -84,7 +84,7 @@ export const staticAssets = (webpackStatsFile) => {
* latest result from a running webpack compiler (i.e. using * latest result from a running webpack compiler (i.e. using
* webpack-dev-middleware). Should only be used in dev. * webpack-dev-middleware). Should only be used in dev.
*/ */
export const devAssets = (webpackCompiler) => { const devAssets = (webpackCompiler) => {
let bundle let bundle
webpackCompiler.plugin('done', (stats) => { webpackCompiler.plugin('done', (stats) => {
bundle = createBundle(stats.toJson()) bundle = createBundle(stats.toJson())
@ -106,7 +106,7 @@ export const devAssets = (webpackCompiler) => {
* Creates a webpack compiler that automatically inlines the * Creates a webpack compiler that automatically inlines the
* webpack dev runtime in all entry points. * webpack dev runtime in all entry points.
*/ */
export const createDevCompiler = (webpackConfig, webpackRuntimeModuleID) => const createDevCompiler = (webpackConfig, webpackRuntimeModuleID) =>
webpack({ webpack({
...webpackConfig, ...webpackConfig,
entry: prependModuleID( entry: prependModuleID(
@ -138,3 +138,10 @@ const prependModuleID = (webpackEntry, moduleID) => {
throw new Error('Invalid webpack entry object') throw new Error('Invalid webpack entry object')
} }
module.exports = {
assetsManifest,
staticAssets,
devAssets,
createDevCompiler
}

View File

@ -1,6 +1,6 @@
import 'isomorphic-fetch' require('isomorphic-fetch')
import { createStack, createFetch, header, base, query, parseJSON, onResponse } from 'http-client' const { createStack, createFetch, header, base, query, parseJSON, onResponse } = require('http-client')
import invariant from 'invariant' const invariant = require('invariant')
const CloudflareKey = process.env.CLOUDFLARE_KEY const CloudflareKey = process.env.CLOUDFLARE_KEY
const CloudflareEmail = process.env.CLOUDFLARE_EMAIL const CloudflareEmail = process.env.CLOUDFLARE_EMAIL
@ -37,19 +37,19 @@ const commonStack = createStack(
getResult() getResult()
) )
export const getZones = (domainName) => const getZones = (domainName) =>
createFetch( createFetch(
commonStack, commonStack,
createNameQuery(domainName) createNameQuery(domainName)
)('/zones') )('/zones')
export const getZoneAnalyticsDashboard = (zone, since, until) => const getZoneAnalyticsDashboard = (zone, since, until) =>
createFetch( createFetch(
commonStack, commonStack,
createRangeQuery(since, until) createRangeQuery(since, until)
)(`/zones/${zone.id}/analytics/dashboard`) )(`/zones/${zone.id}/analytics/dashboard`)
export const getAnalyticsDashboards = (domainNames, since, until) => const getAnalyticsDashboards = (domainNames, since, until) =>
Promise.all( Promise.all(
domainNames.map(domainName => getZones(domainName)) domainNames.map(domainName => getZones(domainName))
).then( ).then(
@ -73,3 +73,9 @@ const reduceResults = (target, results) => {
return target return target
} }
module.exports = {
getZones,
getZoneAnalyticsDashboard,
getAnalyticsDashboards
}

View File

@ -1,7 +1,7 @@
import React from 'react' const React = require('react')
import { renderToStaticMarkup } from 'react-dom/server' const { renderToStaticMarkup } = require('react-dom/server')
import { getAnalyticsDashboards } from './Cloudflare' const { getAnalyticsDashboards } = require('./Cloudflare')
import HomePage from './components/HomePage' const HomePage = require('./components/HomePage')
const OneMinute = 1000 * 60 const OneMinute = 1000 * 60
const ThirtyDays = OneMinute * 60 * 24 * 30 const ThirtyDays = OneMinute * 60 * 24 * 30
@ -19,7 +19,7 @@ const fetchStats = (callback) => {
} }
} }
export const sendHomePage = (req, res, next) => { const sendHomePage = (req, res, next) => {
const chunks = [ 'vendor', 'home' ] const chunks = [ 'vendor', 'home' ]
const props = { const props = {
styles: req.bundle.getStyleAssets(chunks), styles: req.bundle.getStyleAssets(chunks),
@ -41,3 +41,7 @@ export const sendHomePage = (req, res, next) => {
} }
}) })
} }
module.exports = {
sendHomePage
}

View File

@ -1,18 +1,18 @@
import path from 'path' const path = require('path')
export const id = 1 exports.id = 1
export const port = parseInt(process.env.PORT, 10) || 5000 exports.port = parseInt(process.env.PORT, 10) || 5000
export const webpackConfig = require('../../webpack.config') exports.webpackConfig = require('../../webpack.config')
export const statsFile = path.resolve(__dirname, '../../stats.json') exports.statsFile = path.resolve(__dirname, '../../stats.json')
export const publicDir = path.resolve(__dirname, '../../public') exports.publicDir = path.resolve(__dirname, '../../public')
export const manifestFile = path.resolve(publicDir, '__assets__/chunk-manifest.json') exports.manifestFile = path.resolve(exports.publicDir, '__assets__/chunk-manifest.json')
export const timeout = parseInt(process.env.TIMEOUT, 10) || 20000 exports.timeout = parseInt(process.env.TIMEOUT, 10) || 20000
export const maxAge = process.env.MAX_AGE || '365d' exports.maxAge = process.env.MAX_AGE || '365d'
export const registryURL = process.env.REGISTRY_URL || 'https://registry.npmjs.org' exports.registryURL = process.env.REGISTRY_URL || 'https://registry.npmjs.org'
export const bowerBundle = process.env.BOWER_BUNDLE || '/bower.zip' exports.bowerBundle = process.env.BOWER_BUNDLE || '/bower.zip'
export const redirectTTL = process.env.REDIRECT_TTL || 500 exports.redirectTTL = process.env.REDIRECT_TTL || 500
export const autoIndex = !process.env.DISABLE_INDEX exports.autoIndex = !process.env.DISABLE_INDEX
export const redisURL = process.env.REDIS_URL exports.redisURL = process.env.REDIS_URL
export blacklist from '../PackageBlacklist' exports.blacklist = require('../PackageBlacklist')

View File

@ -1,9 +1,9 @@
import redis from 'redis' const redis = require('redis')
import onFinished from 'on-finished' const onFinished = require('on-finished')
const URLFormat = /^\/((?:@[^\/@]+\/)?[^\/@]+)(?:@([^\/]+))?(\/.*)?$/ const URLFormat = /^\/((?:@[^\/@]+\/)?[^\/@]+)(?:@([^\/]+))?(\/.*)?$/
export const logStats = (redisURL) => { const logStats = (redisURL) => {
const redisClient = redis.createClient(redisURL) const redisClient = redis.createClient(redisURL)
return (req, res, next) => { return (req, res, next) => {
@ -25,3 +25,7 @@ export const logStats = (redisURL) => {
next() next()
} }
} }
module.exports = {
logStats
}

View File

@ -1,4 +1,6 @@
import React, { PropTypes } from 'react' const React = require('react')
const PropTypes = React.PropTypes
class HomePage extends React.Component { class HomePage extends React.Component {
static propTypes = { static propTypes = {
@ -43,4 +45,4 @@ class HomePage extends React.Component {
} }
} }
export default HomePage module.exports = HomePage

View File

@ -1,18 +1,18 @@
/*eslint-disable no-console*/ /*eslint-disable no-console*/
import http from 'http' const http = require('http')
import cors from 'cors' const cors = require('cors')
import throng from 'throng' const throng = require('throng')
import morgan from 'morgan' const morgan = require('morgan')
import express from 'express' const express = require('express')
import devErrorHandler from 'errorhandler' const devErrorHandler = require('errorhandler')
import WebpackDevServer from 'webpack-dev-server' const WebpackDevServer = require('webpack-dev-server')
import { createRequestHandler } from 'express-unpkg' const { createRequestHandler } = require('express-unpkg')
import * as DefaultServerConfig from './ServerConfig' const DefaultServerConfig = require('./ServerConfig')
import { assetsManifest, staticAssets, devAssets, createDevCompiler } from './AssetsUtils' const { assetsManifest, staticAssets, devAssets, createDevCompiler } = require('./AssetsUtils')
import { sendHomePage } from './MainController' const { sendHomePage } = require('./MainController')
import { logStats } from './StatsUtils' const { logStats } = require('./StatsUtils')
export const createRouter = (config = {}) => { const createRouter = (config = {}) => {
const router = express.Router() const router = express.Router()
router.get('/', sendHomePage) router.get('/', sendHomePage)
@ -31,7 +31,7 @@ const errorHandler = (err, req, res, next) => {
next(err) next(err)
} }
export const createServer = (config) => { const createServer = (config) => {
const app = express() const app = express()
app.disable('x-powered-by') app.disable('x-powered-by')
@ -67,7 +67,7 @@ export const createServer = (config) => {
return server return server
} }
export const createDevServer = (config) => { const createDevServer = (config) => {
const webpackConfig = config.webpackConfig const webpackConfig = config.webpackConfig
const compiler = createDevCompiler( const compiler = createDevCompiler(
webpackConfig, webpackConfig,
@ -107,7 +107,7 @@ export const createDevServer = (config) => {
return server return server
} }
export const startServer = (serverConfig) => { const startServer = (serverConfig) => {
const config = { const config = {
...DefaultServerConfig, ...DefaultServerConfig,
...serverConfig ...serverConfig
@ -122,6 +122,12 @@ export const startServer = (serverConfig) => {
}) })
} }
module.exports = {
createServer,
createDevServer,
startServer
}
if (require.main === module) if (require.main === module)
throng({ throng({
start: (id) => startServer({ id }), start: (id) => startServer({ id }),