From ec7794c5cda9acf93aec6ccc9a87cd72e81c511f Mon Sep 17 00:00:00 2001 From: Jonas Galvez Date: Sat, 27 Oct 2018 13:48:23 -0300 Subject: [PATCH] refactor(common): nuxt.config.js and dynamic server options to use latest process.env (#4208) --- packages/cli/src/utils.js | 33 +-- packages/cli/test/unit/utils.test.js | 24 +- packages/common/src/config/build.js | 112 ++++++++++ packages/common/src/config/index.js | 128 +++++++++++ packages/common/src/config/messages.js | 12 + packages/common/src/config/render.js | 27 +++ packages/common/src/config/router.js | 13 ++ packages/common/src/config/server.js | 13 ++ packages/common/src/index.js | 1 + packages/common/src/nuxt.config.js | 289 +------------------------ 10 files changed, 325 insertions(+), 327 deletions(-) create mode 100644 packages/common/src/config/build.js create mode 100644 packages/common/src/config/index.js create mode 100644 packages/common/src/config/messages.js create mode 100644 packages/common/src/config/render.js create mode 100644 packages/common/src/config/router.js create mode 100644 packages/common/src/config/server.js diff --git a/packages/cli/src/utils.js b/packages/cli/src/utils.js index 47dcc27bee..8a8b6a6ce7 100644 --- a/packages/cli/src/utils.js +++ b/packages/cli/src/utils.js @@ -3,6 +3,8 @@ import { existsSync } from 'fs' import consola from 'consola' import esm from 'esm' import wrapAnsi from 'wrap-ansi' +import defaultsDeep from 'lodash/defaultsDeep' +import { nuxtServerConfig } from '@nuxt/common' const _require = esm(module, { cache: false, @@ -15,24 +17,6 @@ const _require = esm(module, { const getRootDir = argv => path.resolve(argv._[0] || '.') const getNuxtConfigFile = argv => path.resolve(getRootDir(argv), argv['config-file']) -const getLatestHost = (argv) => { - const port = - argv.port || - process.env.NUXT_PORT || - process.env.PORT || - process.env.npm_package_config_nuxt_port - const host = - argv.hostname || - process.env.NUXT_HOST || - process.env.HOST || - process.env.npm_package_config_nuxt_host - const socket = - argv['unix-socket'] || - process.env.UNIX_SOCKET || - process.env.npm_package_config_unix_socket - - return { port, host, socket } -} export async function loadNuxtConfig(argv) { const rootDir = getRootDir(argv) @@ -70,14 +54,11 @@ export async function loadNuxtConfig(argv) { (argv.spa && 'spa') || (argv.universal && 'universal') || options.mode // Server options - if (!options.server) { - options.server = {} - } - - const { port, host, socket } = getLatestHost(argv) - options.server.port = port || options.server.port || 3000 - options.server.host = host || options.server.host || 'localhost' - options.server.socket = socket || options.server.socket + options.server = defaultsDeep({ + port: argv.port || undefined, + host: argv.hostname || undefined, + socket: argv['unix-socket'] || undefined + }, options.server || {}, nuxtServerConfig(process.env)) return options } diff --git a/packages/cli/test/unit/utils.test.js b/packages/cli/test/unit/utils.test.js index f111aeb932..443cab528c 100644 --- a/packages/cli/test/unit/utils.test.js +++ b/packages/cli/test/unit/utils.test.js @@ -1,3 +1,4 @@ +import { nuxtServerConfig } from '@nuxt/common' import { consola } from '../utils' import * as utils from '../../src/utils' @@ -81,24 +82,19 @@ describe('cli/utils', () => { expect(consola.fatal).toHaveBeenCalledWith('Error while fetching async configuration') }) - test('loadNuxtConfig: server env', async () => { - const env = process.env - - process.env.HOST = 'env-host' - process.env.PORT = 3003 - process.env.UNIX_SOCKET = '/var/run/env.sock' - - const argv = { - _: [__dirname], - 'config-file': '../fixtures/nuxt.config.js' + test('nuxtServerConfig: server env', () => { + const options = { + server: nuxtServerConfig({ + ...process.env, + HOST: 'env-host', + PORT: 3003, + UNIX_SOCKET: '/var/run/env.sock' + }) } - const options = await utils.loadNuxtConfig(argv) expect(options.server.host).toBe('env-host') - expect(options.server.port).toBe('3003') + expect(options.server.port).toBe(3003) expect(options.server.socket).toBe('/var/run/env.sock') - - process.env = env }) test('indent', () => { diff --git a/packages/common/src/config/build.js b/packages/common/src/config/build.js new file mode 100644 index 0000000000..70846ea9ed --- /dev/null +++ b/packages/common/src/config/build.js @@ -0,0 +1,112 @@ +import env from 'std-env' + +export default { + quiet: Boolean(env.ci || env.test), + analyze: false, + profile: process.argv.includes('--profile'), + extractCSS: false, + cssSourceMap: undefined, + ssr: undefined, + parallel: false, + cache: false, + publicPath: '/_nuxt/', + filenames: { + // { isDev, isClient, isServer } + app: ({ isDev }) => isDev ? '[name].js' : '[chunkhash].js', + chunk: ({ isDev }) => isDev ? '[name].js' : '[chunkhash].js', + css: ({ isDev }) => isDev ? '[name].css' : '[contenthash].css', + img: ({ isDev }) => isDev ? '[path][name].[ext]' : 'img/[hash:7].[ext]', + font: ({ isDev }) => isDev ? '[path][name].[ext]' : 'fonts/[hash:7].[ext]', + video: ({ isDev }) => isDev ? '[path][name].[ext]' : 'videos/[hash:7].[ext]' + }, + loaders: { + file: {}, + fontUrl: { limit: 1000 }, + imgUrl: { limit: 1000 }, + pugPlain: {}, + vue: { + transformAssetUrls: { + video: 'src', + source: 'src', + object: 'src', + embed: 'src' + } + }, + css: {}, + cssModules: { + localIdentName: '[local]_[hash:base64:5]' + }, + less: {}, + sass: { + indentedSyntax: true + }, + scss: {}, + stylus: {}, + vueStyle: {} + }, + styleResources: {}, + plugins: [], + terser: {}, + optimizeCSS: undefined, + optimization: { + runtimeChunk: 'single', + minimize: undefined, + minimizer: undefined, + splitChunks: { + chunks: 'all', + automaticNameDelimiter: '.', + name: undefined, + cacheGroups: {} + } + }, + splitChunks: { + layouts: false, + pages: true, + commons: true + }, + babel: { + babelrc: false, + cacheDirectory: undefined + }, + transpile: [], // Name of NPM packages to be transpiled + postcss: { + preset: { + // https://cssdb.org/#staging-process + stage: 2 + } + }, + html: { + minify: { + collapseBooleanAttributes: true, + decodeEntities: true, + minifyCSS: true, + minifyJS: true, + processConditionalComments: true, + removeEmptyAttributes: true, + removeRedundantAttributes: true, + trimCustomFragments: true, + useShortDoctype: true + } + }, + + template: undefined, + templates: [], + + watch: [], + devMiddleware: {}, + hotMiddleware: {}, + + stats: { + chunks: false, + children: false, + modules: false, + colors: true, + warnings: true, + errors: true, + excludeAssets: [ + /.map$/, + /index\..+\.html$/, + /vue-ssr-client-manifest.json/ + ] + } +} diff --git a/packages/common/src/config/index.js b/packages/common/src/config/index.js new file mode 100644 index 0000000000..c9bd2a93dd --- /dev/null +++ b/packages/common/src/config/index.js @@ -0,0 +1,128 @@ +import path from 'path' +import fs from 'fs' +import capitalize from 'lodash/capitalize' +import env from 'std-env' + +import render from './render' +import build from './build' +import router from './router' +import messages from './messages' +import server from './server' + +const nuxtDir = fs.existsSync(path.resolve(__dirname, '..', '..', 'package.js')) + ? path.resolve(__dirname, '..', '..') // src + : path.resolve(__dirname, '..') // dist + +export default { + // Information about running environment + dev: Boolean(env.dev), + test: Boolean(env.test), + debug: undefined, // = dev + + // Mode + mode: 'universal', + + // Global name + globalName: `nuxt`, + globals: { + id: globalName => `__${globalName}`, + nuxt: globalName => `$${globalName}`, + context: globalName => `__${globalName.toUpperCase()}__`, + pluginPrefix: globalName => globalName, + readyCallback: globalName => `on${capitalize(globalName)}Ready`, + loadedCallback: globalName => `_on${capitalize(globalName)}Loaded` + }, + + render, + build, + router, + messages, + + // Server options + server: server(process.env), + + // Dirs + srcDir: undefined, + buildDir: '.nuxt', + nuxtDir, + modulesDir: [ + 'node_modules' + ], + + // Ignore + ignorePrefix: '-', + ignore: [ + '**/*.test.*', + '**/*.spec.*' + ], + + extensions: [], + + generate: { + dir: 'dist', + routes: [], + concurrency: 500, + interval: 0, + subFolders: true, + fallback: '200.html' + }, + env: {}, + head: { + meta: [], + link: [], + style: [], + script: [] + }, + plugins: [], + css: [], + modules: [], + layouts: {}, + serverMiddleware: [], + ErrorPage: null, + loading: { + color: 'black', + failedColor: 'red', + height: '2px', + throttle: 200, + duration: 5000, + rtl: false + }, + loadingIndicator: 'default', + transition: { + name: 'page', + mode: 'out-in', + appear: false, + appearClass: 'appear', + appearActiveClass: 'appear-active', + appearToClass: 'appear-to' + }, + layoutTransition: { + name: 'layout', + mode: 'out-in' + }, + dir: { + assets: 'assets', + layouts: 'layouts', + middleware: 'middleware', + pages: 'pages', + static: 'static', + store: 'store' + }, + vue: { + config: { + silent: undefined, // = !dev + performance: undefined // = dev + } + }, + + // User-defined changes + watch: [], + watchers: { + webpack: {}, + chokidar: { + ignoreInitial: true + } + }, + editor: undefined, + hooks: null +} diff --git a/packages/common/src/config/messages.js b/packages/common/src/config/messages.js new file mode 100644 index 0000000000..34a2dda4bf --- /dev/null +++ b/packages/common/src/config/messages.js @@ -0,0 +1,12 @@ +export default { + loading: 'Loading...', + error_404: 'This page could not be found', + server_error: 'Server error', + nuxtjs: 'Nuxt.js', + back_to_home: 'Back to the home page', + server_error_details: + 'An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details.', + client_error: 'Error', + client_error_details: + 'An error occurred while rendering the page. Check developer tools console for details.' +} diff --git a/packages/common/src/config/render.js b/packages/common/src/config/render.js new file mode 100644 index 0000000000..da9dd2c4d0 --- /dev/null +++ b/packages/common/src/config/render.js @@ -0,0 +1,27 @@ +export default { + bundleRenderer: { + shouldPrefetch: () => false + }, + resourceHints: true, + ssr: undefined, + http2: { + push: false, + shouldPush: null + }, + static: { + prefix: true + }, + compressor: { + threshold: 0 + }, + etag: { + weak: false + }, + csp: false, + dist: { + // Don't serve index.html template + index: false, + // 1 year in production + maxAge: '1y' + } +} diff --git a/packages/common/src/config/router.js b/packages/common/src/config/router.js new file mode 100644 index 0000000000..8d3c8fcb53 --- /dev/null +++ b/packages/common/src/config/router.js @@ -0,0 +1,13 @@ +export default { + mode: 'history', + base: '/', + routes: [], + middleware: [], + linkActiveClass: 'nuxt-link-active', + linkExactActiveClass: 'nuxt-link-exact-active', + extendRoutes: null, + scrollBehavior: null, + parseQuery: false, + stringifyQuery: false, + fallback: false +} diff --git a/packages/common/src/config/server.js b/packages/common/src/config/server.js new file mode 100644 index 0000000000..9bdbaef1a9 --- /dev/null +++ b/packages/common/src/config/server.js @@ -0,0 +1,13 @@ +export default env => ({ + https: false, + port: env.NUXT_PORT || + env.PORT || + env.npm_package_config_nuxt_port || + 3000, + host: env.NUXT_HOST || + env.HOST || + env.npm_package_config_nuxt_host || + 'localhost', + socket: env.UNIX_SOCKET || + env.npm_package_config_unix_socket +}) diff --git a/packages/common/src/index.js b/packages/common/src/index.js index 80f0717de8..ce636223c6 100644 --- a/packages/common/src/index.js +++ b/packages/common/src/index.js @@ -1,5 +1,6 @@ export { default as Modes } from './modes' export { default as NuxtConfig } from './nuxt.config' +export { default as nuxtServerConfig } from './config/server' export { default as Options } from './options' export { default as BuildContext } from './build/context' export * from './utils' diff --git a/packages/common/src/nuxt.config.js b/packages/common/src/nuxt.config.js index 9d8f2ed90c..657adb95f7 100644 --- a/packages/common/src/nuxt.config.js +++ b/packages/common/src/nuxt.config.js @@ -1,288 +1,3 @@ -import path from 'path' -import fs from 'fs' -import capitalize from 'lodash/capitalize' -import env from 'std-env' +import config from './config' -const nuxtDir = fs.existsSync(path.resolve(__dirname, '..', '..', 'package.js')) - ? path.resolve(__dirname, '..', '..') // src - : path.resolve(__dirname, '..') // dist - -export default { - // Information about running environment - dev: Boolean(env.dev), - test: Boolean(env.test), - debug: undefined, // = dev - - // Mode - mode: 'universal', - - // Global name - globalName: `nuxt`, - globals: { - id: globalName => `__${globalName}`, - nuxt: globalName => `$${globalName}`, - context: globalName => `__${globalName.toUpperCase()}__`, - pluginPrefix: globalName => globalName, - readyCallback: globalName => `on${capitalize(globalName)}Ready`, - loadedCallback: globalName => `_on${capitalize(globalName)}Loaded` - }, - - // Server options - server: { - https: false, - port: process.env.NUXT_PORT || - process.env.PORT || - process.env.npm_package_config_nuxt_port || - '3000', - host: process.env.NUXT_HOST || - process.env.HOST || - process.env.npm_package_config_nuxt_host || - 'localhost' - }, - - // Dirs - srcDir: undefined, - buildDir: '.nuxt', - nuxtDir, - modulesDir: [ - 'node_modules' - ], - - // Ignore - ignorePrefix: '-', - ignore: [ - '**/*.test.*', - '**/*.spec.*' - ], - - extensions: [], - - build: { - quiet: Boolean(env.ci || env.test), - analyze: false, - profile: process.argv.includes('--profile'), - extractCSS: false, - cssSourceMap: undefined, - ssr: undefined, - parallel: false, - cache: false, - publicPath: '/_nuxt/', - filenames: { - // { isDev, isClient, isServer } - app: ({ isDev }) => isDev ? '[name].js' : '[chunkhash].js', - chunk: ({ isDev }) => isDev ? '[name].js' : '[chunkhash].js', - css: ({ isDev }) => isDev ? '[name].css' : '[contenthash].css', - img: ({ isDev }) => isDev ? '[path][name].[ext]' : 'img/[hash:7].[ext]', - font: ({ isDev }) => isDev ? '[path][name].[ext]' : 'fonts/[hash:7].[ext]', - video: ({ isDev }) => isDev ? '[path][name].[ext]' : 'videos/[hash:7].[ext]' - }, - loaders: { - file: {}, - fontUrl: { limit: 1000 }, - imgUrl: { limit: 1000 }, - pugPlain: {}, - vue: { - transformAssetUrls: { - video: 'src', - source: 'src', - object: 'src', - embed: 'src' - } - }, - css: {}, - cssModules: { - localIdentName: '[local]_[hash:base64:5]' - }, - less: {}, - sass: { - indentedSyntax: true - }, - scss: {}, - stylus: {}, - vueStyle: {} - }, - styleResources: {}, - plugins: [], - terser: {}, - optimizeCSS: undefined, - optimization: { - runtimeChunk: 'single', - minimize: undefined, - minimizer: undefined, - splitChunks: { - chunks: 'all', - automaticNameDelimiter: '.', - name: undefined, - cacheGroups: {} - } - }, - splitChunks: { - layouts: false, - pages: true, - commons: true - }, - babel: { - babelrc: false, - cacheDirectory: undefined - }, - transpile: [], // Name of NPM packages to be transpiled - postcss: { - preset: { - // https://cssdb.org/#staging-process - stage: 2 - } - }, - html: { - minify: { - collapseBooleanAttributes: true, - decodeEntities: true, - minifyCSS: true, - minifyJS: true, - processConditionalComments: true, - removeEmptyAttributes: true, - removeRedundantAttributes: true, - trimCustomFragments: true, - useShortDoctype: true - } - }, - - template: undefined, - templates: [], - - watch: [], - devMiddleware: {}, - hotMiddleware: {}, - - stats: { - chunks: false, - children: false, - modules: false, - colors: true, - warnings: true, - errors: true, - excludeAssets: [ - /.map$/, - /index\..+\.html$/, - /vue-ssr-client-manifest.json/ - ] - } - }, - generate: { - dir: 'dist', - routes: [], - concurrency: 500, - interval: 0, - subFolders: true, - fallback: '200.html' - }, - env: {}, - head: { - meta: [], - link: [], - style: [], - script: [] - }, - plugins: [], - css: [], - modules: [], - layouts: {}, - serverMiddleware: [], - ErrorPage: null, - loading: { - color: 'black', - failedColor: 'red', - height: '2px', - throttle: 200, - duration: 5000, - rtl: false - }, - loadingIndicator: 'default', - transition: { - name: 'page', - mode: 'out-in', - appear: false, - appearClass: 'appear', - appearActiveClass: 'appear-active', - appearToClass: 'appear-to' - }, - layoutTransition: { - name: 'layout', - mode: 'out-in' - }, - dir: { - assets: 'assets', - layouts: 'layouts', - middleware: 'middleware', - pages: 'pages', - static: 'static', - store: 'store' - }, - vue: { - config: { - silent: undefined, // = !dev - performance: undefined // = dev - } - }, - router: { - mode: 'history', - base: '/', - routes: [], - middleware: [], - linkActiveClass: 'nuxt-link-active', - linkExactActiveClass: 'nuxt-link-exact-active', - extendRoutes: null, - scrollBehavior: null, - parseQuery: false, - stringifyQuery: false, - fallback: false - }, - render: { - bundleRenderer: { - shouldPrefetch: () => false - }, - resourceHints: true, - ssr: undefined, - http2: { - push: false, - shouldPush: null - }, - static: { - prefix: true - }, - compressor: { - threshold: 0 - }, - etag: { - weak: false - }, - csp: false, - dist: { - // Don't serve index.html template - index: false, - // 1 year in production - maxAge: '1y' - } - }, - // User-defined changes - watch: [], - watchers: { - webpack: {}, - chokidar: { - ignoreInitial: true - } - }, - editor: undefined, - hooks: null, - messages: { - loading: 'Loading...', - error_404: 'This page could not be found', - server_error: 'Server error', - nuxtjs: 'Nuxt.js', - back_to_home: 'Back to the home page', - server_error_details: - 'An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details.', - client_error: 'Error', - client_error_details: - 'An error occurred while rendering the page. Check developer tools console for details.' - } -} +export default config