Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// 外部パッケージをインストール
import webpack from 'webpack'
import WebpackDevServer from "webpack-dev-server"
import express from 'express'
import graphQLHTTP from 'express-graphql'
import chokidar from 'chokidar'
// 標準パッケージをインストール
import path from 'path'
import { exec } from 'child_process'
// webpack config
import config from './webpack.config.js'
// posts
const APP_PORT = 3000
const WEBPACK_GRAPHQL_PORT = 8080
// server variables
let graphQLServer
let appServer
// add webpack dev server config
config.entry.client.push("webpack-dev-server/client?http://localhost:8080")
config.entry.client.push("webpack/hot/dev-server")
config.plugins.push(new webpack.HotModuleReplacementPlugin())
// server where we develop
function startAppServer(callback) {
const compiler = webpack(config)
appServer = new WebpackDevServer(compiler, {
proxy: {'/graphql': `http://localhost:${WEBPACK_GRAPHQL_PORT}`},
publicPath: config.output.publicPath,
hot: true,
stats: {colors: true}
})
appServer.use('/', express.static(path.resolve(__dirname, 'public')))
appServer.listen(APP_PORT, () => {
console.log(`App is now running on http://localhost:${APP_PORT}`)
if(callback) {
callback()
}
})
}
// server where we see GraphQL
function startGraphQLServer(callback) {
const { Schema } = require('./data/schema')
const graphQLApp = express()
graphQLApp.use('/', graphQLHTTP({
graphql: true,
pretty: true,
schema: Schema,
}))
graphQLServer = graphQLApp.listen(WEBPACK_GRAPHQL_PORT, () => {
console.log(`GraphQL server is now running on http://localhost:${WEBPACK_GRAPHQL_PORT}`)
if(callback) {
callback()
}
})
}
// start both servers and stay for listening
function startServers(callback) {
if(appServer) {
appServer.listeningApp.close()
}
if(graphQLServer) {
graphQLServer.close()
}
exec('npm run update-schema', (error, stdout) => {
console.log(stdout)
let doneTasks = 0
function handleTaskDone() {
doneTasks++
if(doneTasks === 2 && callback) {
callback()
}
}
startGraphQLServer(handleTaskDone)
startAppServer(handleTaskDone)
})
// watch
const watcher = chokidar.watch('./data/{database, schema}.js')
watcher.on('change', path => {
console.log(`\`${path}\` changed. Restarting.`);
startServers(() => {
console.log('Restart your browser to use the updated schema.')
})
})
}
// FIRE!!!
startServers()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment