Unverified Commit fbaeba49 authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Add CONFIG_FILE constant, add types for server/config.js (#4529)

This was pulled from #4518, it can already be merged so it's easier to get it in.
parent 905da6f9
...@@ -2,6 +2,7 @@ ...@@ -2,6 +2,7 @@
import { join } from 'path' import { join } from 'path'
import { spawn } from 'cross-spawn' import { spawn } from 'cross-spawn'
import pkg from '../../package.json' import pkg from '../../package.json'
import {CONFIG_FILE} from '../lib/constants'
if (pkg.peerDependencies) { if (pkg.peerDependencies) {
Object.keys(pkg.peerDependencies).forEach(dependency => { Object.keys(pkg.peerDependencies).forEach(dependency => {
...@@ -89,9 +90,9 @@ let proc = startProcess() ...@@ -89,9 +90,9 @@ let proc = startProcess()
if (cmd === 'dev') { if (cmd === 'dev') {
const {watchFile} = require('fs') const {watchFile} = require('fs')
watchFile(`${process.cwd()}/next.config.js`, (cur, prev) => { watchFile(`${process.cwd()}/${CONFIG_FILE}`, (cur, prev) => {
if (cur.size > 0 || prev.size > 0) { if (cur.size > 0 || prev.size > 0) {
console.log('\n> Found a change in next.config.js, restarting the server...') console.log(`\n> Found a change in ${CONFIG_FILE}, restarting the server...`)
// Don't listen to 'close' now since otherwise parent gets killed by listener // Don't listen to 'close' now since otherwise parent gets killed by listener
proc.removeAllListeners('close') proc.removeAllListeners('close')
proc.kill() proc.kill()
......
...@@ -5,3 +5,4 @@ export const PHASE_DEVELOPMENT_SERVER = 'phase-development-server' ...@@ -5,3 +5,4 @@ export const PHASE_DEVELOPMENT_SERVER = 'phase-development-server'
export const PAGES_MANIFEST = 'pages-manifest.json' export const PAGES_MANIFEST = 'pages-manifest.json'
export const BUILD_MANIFEST = 'build-manifest.json' export const BUILD_MANIFEST = 'build-manifest.json'
export const SERVER_DIRECTORY = 'server' export const SERVER_DIRECTORY = 'server'
export const CONFIG_FILE = 'next.config.js'
...@@ -2,7 +2,7 @@ import { join } from 'path' ...@@ -2,7 +2,7 @@ import { join } from 'path'
import promisify from '../lib/promisify' import promisify from '../lib/promisify'
import fs from 'fs' import fs from 'fs'
import webpack from 'webpack' import webpack from 'webpack'
import getConfig from '../config' import loadConfig from '../config'
import { PHASE_PRODUCTION_BUILD } from '../../lib/constants' import { PHASE_PRODUCTION_BUILD } from '../../lib/constants'
import getBaseWebpackConfig from './webpack' import getBaseWebpackConfig from './webpack'
...@@ -10,7 +10,7 @@ const access = promisify(fs.access) ...@@ -10,7 +10,7 @@ const access = promisify(fs.access)
const writeFile = promisify(fs.writeFile) const writeFile = promisify(fs.writeFile)
export default async function build (dir, conf = null) { export default async function build (dir, conf = null) {
const config = getConfig(PHASE_PRODUCTION_BUILD, dir, conf) const config = loadConfig(PHASE_PRODUCTION_BUILD, dir, conf)
const buildId = await config.generateBuildId() // defaults to a uuid const buildId = await config.generateBuildId() // defaults to a uuid
try { try {
......
// @flow // @flow
import findUp from 'find-up' import findUp from 'find-up'
import uuid from 'uuid' import uuid from 'uuid'
import {CONFIG_FILE} from '../lib/constants'
const cache = new Map()
type WebpackConfig = *
const defaultConfig = {
type WebpackDevMiddlewareConfig = *
export type NextConfig = {|
webpack: null | (webpackConfig: WebpackConfig, {dir: string, dev: boolean, isServer: boolean, buildId: string, config: NextConfig, defaultLoaders: {}, totalPages: number}) => WebpackConfig,
webpackDevMiddleware: null | (WebpackDevMiddlewareConfig: WebpackDevMiddlewareConfig) => WebpackDevMiddlewareConfig,
poweredByHeader: boolean,
distDir: string,
assetPrefix: string,
configOrigin: string,
useFileSystemPublicRoutes: boolean,
generateBuildId: () => string,
generateEtags: boolean,
pageExtensions: Array<string>
|}
const defaultConfig: NextConfig = {
webpack: null, webpack: null,
webpackDevMiddleware: null, webpackDevMiddleware: null,
poweredByHeader: true, poweredByHeader: true,
...@@ -17,37 +33,28 @@ const defaultConfig = { ...@@ -17,37 +33,28 @@ const defaultConfig = {
pageExtensions: ['jsx', 'js'] pageExtensions: ['jsx', 'js']
} }
export default function getConfig (phase: string, dir: string, customConfig?: ?Object) { type PhaseFunction = (phase: string, options: {defaultConfig: NextConfig}) => NextConfig
if (!cache.has(dir)) {
cache.set(dir, loadConfig(phase, dir, customConfig))
}
return cache.get(dir)
}
export function loadConfig (phase: string, dir: string, customConfig?: ?Object) { export default function loadConfig (phase: string, dir: string, customConfig?: NextConfig): NextConfig {
if (customConfig && typeof customConfig === 'object') { if (customConfig) {
customConfig.configOrigin = 'server' customConfig.configOrigin = 'server'
return withDefaults(customConfig) return {...defaultConfig, ...customConfig}
} }
const path: string = findUp.sync('next.config.js', { const path: string = findUp.sync(CONFIG_FILE, {
cwd: dir cwd: dir
}) })
let userConfig = {} // If config file was found
if (path && path.length) { if (path && path.length) {
// $FlowFixMe // $FlowFixMe
const userConfigModule = require(path) const userConfigModule = require(path)
userConfig = userConfigModule.default || userConfigModule const userConfigInitial: NextConfig | PhaseFunction = userConfigModule.default || userConfigModule
if (typeof userConfigModule === 'function') { if (typeof userConfigInitial === 'function') {
userConfig = userConfigModule(phase, {defaultConfig}) return {...defaultConfig, configOrigin: CONFIG_FILE, ...userConfigInitial(phase, {defaultConfig})}
} }
userConfig.configOrigin = 'next.config.js'
}
return withDefaults(userConfig) return {...defaultConfig, configOrigin: CONFIG_FILE, ...userConfigInitial}
} }
function withDefaults (config: Object) { return defaultConfig
return Object.assign({}, defaultConfig, config)
} }
...@@ -4,8 +4,8 @@ import mkdirp from 'mkdirp-then' ...@@ -4,8 +4,8 @@ import mkdirp from 'mkdirp-then'
import walk from 'walk' import walk from 'walk'
import { extname, resolve, join, dirname, sep } from 'path' import { extname, resolve, join, dirname, sep } from 'path'
import { existsSync, readFileSync, writeFileSync } from 'fs' import { existsSync, readFileSync, writeFileSync } from 'fs'
import getConfig from './config' import loadConfig from './config'
import {PHASE_EXPORT, SERVER_DIRECTORY, PAGES_MANIFEST} from '../lib/constants' import {PHASE_EXPORT, SERVER_DIRECTORY, PAGES_MANIFEST, CONFIG_FILE} from '../lib/constants'
import { renderToHTML } from './render' import { renderToHTML } from './render'
import { getAvailableChunks } from './utils' import { getAvailableChunks } from './utils'
import { setAssetPrefix } from '../lib/asset' import { setAssetPrefix } from '../lib/asset'
...@@ -13,7 +13,7 @@ import * as envConfig from '../lib/runtime-config' ...@@ -13,7 +13,7 @@ import * as envConfig from '../lib/runtime-config'
export default async function (dir, options, configuration) { export default async function (dir, options, configuration) {
dir = resolve(dir) dir = resolve(dir)
const nextConfig = configuration || getConfig(PHASE_EXPORT, dir) const nextConfig = configuration || loadConfig(PHASE_EXPORT, dir)
const nextDir = join(dir, nextConfig.distDir) const nextDir = join(dir, nextConfig.distDir)
log(`> using build directory: ${nextDir}`) log(`> using build directory: ${nextDir}`)
...@@ -73,9 +73,9 @@ export default async function (dir, options, configuration) { ...@@ -73,9 +73,9 @@ export default async function (dir, options, configuration) {
await copyPages(nextDir, outDir, buildId) await copyPages(nextDir, outDir, buildId)
// Get the exportPathMap from the `next.config.js` // Get the exportPathMap from the config file
if (typeof nextConfig.exportPathMap !== 'function') { if (typeof nextConfig.exportPathMap !== 'function') {
console.log('> No "exportPathMap" found in "next.config.js". Generating map from "./pages"') console.log(`> No "exportPathMap" found in "${CONFIG_FILE}". Generating map from "./pages"`)
nextConfig.exportPathMap = async (defaultMap) => { nextConfig.exportPathMap = async (defaultMap) => {
return defaultMap return defaultMap
} }
......
...@@ -14,15 +14,16 @@ import { ...@@ -14,15 +14,16 @@ import {
} from './render' } from './render'
import Router from './router' import Router from './router'
import { getAvailableChunks, isInternalUrl } from './utils' import { getAvailableChunks, isInternalUrl } from './utils'
import getConfig from './config' import loadConfig from './config'
import {PHASE_PRODUCTION_SERVER, PHASE_DEVELOPMENT_SERVER} from '../lib/constants' import {PHASE_PRODUCTION_SERVER, PHASE_DEVELOPMENT_SERVER} from '../lib/constants'
// We need to go up one more level since we are in the `dist` directory
import pkg from '../../package'
import * as asset from '../lib/asset' import * as asset from '../lib/asset'
import * as envConfig from '../lib/runtime-config' import * as envConfig from '../lib/runtime-config'
import { isResSent } from '../lib/utils' import { isResSent } from '../lib/utils'
import isAsyncSupported from './lib/is-async-supported' import isAsyncSupported from './lib/is-async-supported'
// We need to go up one more level since we are in the `dist` directory
import pkg from '../../package'
const access = promisify(fs.access) const access = promisify(fs.access)
const blockedPages = { const blockedPages = {
...@@ -39,7 +40,7 @@ export default class Server { ...@@ -39,7 +40,7 @@ export default class Server {
this.router = new Router() this.router = new Router()
this.http = null this.http = null
const phase = dev ? PHASE_DEVELOPMENT_SERVER : PHASE_PRODUCTION_SERVER const phase = dev ? PHASE_DEVELOPMENT_SERVER : PHASE_PRODUCTION_SERVER
this.nextConfig = getConfig(phase, this.dir, conf) this.nextConfig = loadConfig(phase, this.dir, conf)
this.dist = this.nextConfig.distDir this.dist = this.nextConfig.distDir
this.hotReloader = dev ? this.getHotReloader(this.dir, { quiet, config: this.nextConfig }) : null this.hotReloader = dev ? this.getHotReloader(this.dir, { quiet, config: this.nextConfig }) : null
......
/* global describe, it, expect */ /* global describe, it, expect */
import {join} from 'path' import {join} from 'path'
import getConfig, {loadConfig} from '../../dist/server/config' import loadConfig from '../../dist/server/config'
import {PHASE_DEVELOPMENT_SERVER} from '../../dist/lib/constants' import {PHASE_DEVELOPMENT_SERVER} from '../../dist/lib/constants'
const pathToConfig = join(__dirname, '_resolvedata', 'without-function') const pathToConfig = join(__dirname, '_resolvedata', 'without-function')
...@@ -32,10 +32,4 @@ describe('config', () => { ...@@ -32,10 +32,4 @@ describe('config', () => {
const config = loadConfig(PHASE_DEVELOPMENT_SERVER, null, null) const config = loadConfig(PHASE_DEVELOPMENT_SERVER, null, null)
expect(config.webpack).toBe(null) expect(config.webpack).toBe(null)
}) })
it('Should cache on getConfig', () => {
const config = getConfig(PHASE_DEVELOPMENT_SERVER, pathToConfig)
const config2 = getConfig(PHASE_DEVELOPMENT_SERVER, pathToConfig, {extraConfig: true}) // won't add extraConfig because it's cached.
expect(config === config2).toBe(true)
})
}) })
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment