Nuxt/packages/config/test/options.test.js
Sébastien Chopin 917adc0618
feat: options.target and full-static export (#6159)
* feat: add options.target

* fix(lint): lint

* fix(test): update snapshots

* fix(builder): default value for target

* fix(test): fix test

* fix(test): test fixing

* fix: use this.options.target

* fix: final test

* Update packages/vue-renderer/src/renderer.js

Co-Authored-By: Alexander Lichter <manniL@gmx.net>

* feat: Add target option and update banner

* fix(lint): fix

* feat: Add warning when using serverMiddleware in static target

* chore(utils): add TARGETS and MODES as constants

* hotfix: lint

* chore(module): add filename as alias of fileName

* feat: introducing nuxt export and router/routes.json

* hotfix: Fix the linting lord

* chore(core): add comment for filename vs fileName

* fix: use targets constant

* chore: remove warning

* fix: unit testing

* wip: refactor and use TARGETS

* fix: lint

* feat: add target as alias for first arg value

* fix: generate only for SPA

* chore: explain to use nuxt static X

* fix: render SPA fallback on redirect for static target

* fix: lint issue

* fix: only target is useful for now

* wip

* wip: nuxt static export is looking good

* Update packages/generator/src/generator.js

Co-Authored-By: Devon Rueckner <indirectlylit@users.noreply.github.com>

* Update packages/cli/src/options/common.js

Co-Authored-By: Alexander Lichter <manniL@gmx.net>

* feat: add options.target

* fix(lint): lint

* fix(test): update snapshots

* fix(builder): default value for target

* fix(test): fix test

* fix(test): test fixing

* fix: use this.options.target

* fix: final test

* Update packages/vue-renderer/src/renderer.js

Co-Authored-By: Alexander Lichter <manniL@gmx.net>

* feat: Add target option and update banner

* fix(lint): fix

* feat: Add warning when using serverMiddleware in static target

* chore(utils): add TARGETS and MODES as constants

* hotfix: lint

* chore(module): add filename as alias of fileName

* feat: introducing nuxt export and router/routes.json

* hotfix: Fix the linting lord

* chore(core): add comment for filename vs fileName

* fix: use targets constant

* chore: remove warning

* fix: unit testing

* wip: refactor and use TARGETS

* fix: lint

* feat: add target as alias for first arg value

* chore: explain to use nuxt static X

* fix: render SPA fallback on redirect for static target

* fix: lint issue

* fix: only target is useful for now

* wip

* wip: nuxt static export is looking good

* Update packages/generator/src/generator.js

Co-Authored-By: Devon Rueckner <indirectlylit@users.noreply.github.com>

* Update packages/cli/src/options/common.js

Co-Authored-By: Alexander Lichter <manniL@gmx.net>

* fix: duplicate imports

* chore: don't server render if an error happens on static target

* test: update unit and add export

* lint: fix

* lint: fix

* fix: e2e test

* fix: fallback only for static target

* fix: dev test

* feat: add generate.crawler

* fix: full static is when generate.static is given

* chore: improvements

* fix: Add isFullStatic in nuxt/config.json

* feat: handle fetch for full static

* feat: router.prefetchPayloads for full static

* chore: use fetch in async-data example

* fix: add target only if given

* fix: use created to have access to props in fetchOnServer

* chore: add console.error in dev for easy debugging

* feat: payload smart pre-fetching

* fix: remove alias for target

* fix: increment payloadFetchIndex is static set to false

* chore: lint

* chore: add serve command

* chore: rename universal to server-side

* fix: handle payloadPath on SPA fallback

* fix: lint

* chore lint again

* feat: handle spa fallback

* feat: support string for exclude

* fix: fallback only if no extension or html

* chore: use JSON.stringify() for static target

* chore: lint again, dammit

* chore: fix tests and remove too early return

* fix: early return only for server target

* fix: update tests

* fix: unit tests

* chore: add ssr option

* chore: add logic for ssr option

* fix: #6682

* chore(dx): add next command to run

* fix: lint

* fix: tests

* chore: keep old behaviour for nuxt build in spa

* fix: test again, oh boy

* fix: alright this is good now

* chore: add comment for spa fallback

* chore: move routes.json to dot nuxt dir

* chore: simplify check for promise

* chore: unique lock id

* chore: refactor isFullStatic

* fix: dont set default in build context

* chore: add test for serve

* chore: update tests

* hotfix: lint tests

* chore(dx): improve message for bundling

* feat: js payload extraction with jsonp

* fix: keep serialized session script for legacy generate

* fix: call to setPagePayload from fetchPayload

* use devalue for payload chunks

* feat: add initial load state chunk

* feat: preload payload and state scripts

* fix(vue-app): don't re-render the app if trailing slash on SSG

* hotfix: remove console.log

* chore(dx): add deploy infos for nuxt export

Co-authored-by: Pooya Parsa <pyapar@gmail.com>

* chore: handle fetching payload.js for nuxt state

* chore(dx): error when using nuxt generate and static

* chore: remove static option for clarity

* chore: remove serverless target

* hotfix: lint

* hotfix: unit tests

* chore: update legacy js resource

* chore: remove query params from url in static target

* fix: use globalName and urlJoin

* chore: typo

* feat: previewMode 👀

* chore: rename to enablePreview

* fix: wait next tick to avoid error on spa

* chore: try 1 sec

* hotfix: test only for linux, wtf azure

* refactor: static assets

- generalize logic for modules need emit export static assets
- allow customization for version, dir and base
- serialization logic is only in ssr now

* feat: smart state chunk creates

* fix(client): ignore payload load error

* perf: avoide payload loading for spa initial

* perf: avoid loading failed chunks again

* chore(cli): add simple compression for nuxt serve

* test: update snapshots

* fix version snapshot

* fix(generator): set staticAssetsBase on context only for full static

* fix tests

* fix: honor shouldHashCspScriptSrc

* chore(dx): add log for client-side fallback creation

Co-authored-by: Xin Du (Clark) <clark.duxin@gmail.com>
Co-authored-by: Alexander Lichter <manniL@gmx.net>
Co-authored-by: Pooya Parsa <pooya@pi0.ir>
Co-authored-by: Devon Rueckner <indirectlylit@users.noreply.github.com>
Co-authored-by: Pooya Parsa <pyapar@gmail.com>
2020-05-07 21:08:01 +02:00

317 lines
12 KiB
JavaScript

import path from 'path'
import consola from 'consola'
import { getNuxtConfig } from '../src/options'
jest.mock('std-env', () => ({
browser: false,
test: 'test',
dev: false,
production: true,
debug: false,
ci: true,
windows: false,
darwin: false,
linux: true
}))
jest.mock('@nuxt/utils', () => ({
...jest.requireActual('@nuxt/utils'),
getMainModule: () => ({ paths: ['/var/nuxt/node_modules'] })
}))
describe('config: options', () => {
test('should return default nuxt config', () => {
jest.spyOn(process, 'cwd').mockReturnValue('/var/nuxt/test')
jest.spyOn(path, 'resolve').mockImplementation((...args) => args.join('/').replace(/\\+/, '/'))
jest.spyOn(path, 'join').mockImplementation((...args) => args.join('/').replace(/\\+/, '/'))
expect(getNuxtConfig({ generate: { staticAssets: { version: 'x' } } })).toMatchSnapshot()
process.cwd.mockRestore()
path.resolve.mockRestore()
path.join.mockRestore()
})
test('should prevent duplicate calls with same options', () => {
const options = {}
const firstConfig = getNuxtConfig(options)
const secondConfig = getNuxtConfig(firstConfig)
expect(firstConfig).toBe(secondConfig)
expect(firstConfig.__normalized__).toBe(true)
})
test('should return default loading when loading is true', () => {
const { loading } = getNuxtConfig({ loading: true })
expect(loading).toEqual({
color: 'black',
failedColor: 'red',
height: '2px',
throttle: 200,
duration: 5000,
continuous: false,
rtl: false,
css: true
})
})
test('[Compatibility] should transform transition to pageTransition', () => {
const { pageTransition, transition } = getNuxtConfig({
transition: 'test-tran'
})
expect(pageTransition).toMatchObject({ name: 'test-tran' })
expect(transition).toBeUndefined()
})
test('should transform pageTransition/layoutTransition to name', () => {
const { pageTransition, layoutTransition } = getNuxtConfig({
pageTransition: 'test-tran',
layoutTransition: 'test-layout-tran'
})
expect(pageTransition).toMatchObject({ name: 'test-tran' })
expect(layoutTransition).toMatchObject({ name: 'test-layout-tran' })
})
test('should transform extensions to array', () => {
const { extensions } = getNuxtConfig({ extensions: 'ext' })
expect(extensions).toEqual(['js', 'mjs', 'ext'])
})
test('should support custom global name', () => {
const { globalName } = getNuxtConfig({ globalName: 'globalNuxt' })
expect(globalName).toEqual('globalnuxt')
})
test('should detect store dir', () => {
const { store } = getNuxtConfig({ rootDir: path.resolve(__dirname, 'fixtures') })
expect(store).toEqual(true)
})
test('should unset and warn when etag.hash not a function', () => {
const { render: { etag } } = getNuxtConfig({ render: { etag: { hash: true } } })
expect(etag).toMatchObject({ hash: undefined })
expect(consola.warn).not.toHaveBeenCalledWith('render.etag.hash should be a function, received boolean instead')
const { render: { etag: etagDev } } = getNuxtConfig({ dev: true, render: { etag: { hash: true } } })
expect(etagDev).toMatchObject({ hash: undefined })
expect(consola.warn).toHaveBeenCalledWith('render.etag.hash should be a function, received boolean instead')
})
test('should enable csp', () => {
const { render: { csp } } = getNuxtConfig({ render: { csp: { allowedSources: ['/nuxt/*'], test: true } } })
expect(csp).toEqual({
hashAlgorithm: 'sha256',
addMeta: false,
unsafeInlineCompatibility: false,
allowedSources: ['/nuxt/*'],
policies: undefined,
reportOnly: false,
test: true
})
})
// TODO: Remove this test in Nuxt 3, we will stop supporting this typo (more on: https://github.com/nuxt/nuxt.js/pull/6583)
test('should enable csp with old typo property name, avoiding breaking changes', () => {
const { render: { csp } } = getNuxtConfig({ render: { csp: { allowedSources: ['/nuxt/*'], test: true, unsafeInlineCompatiblity: true } } })
expect(csp).toEqual({
hashAlgorithm: 'sha256',
addMeta: false,
unsafeInlineCompatibility: true,
allowedSources: ['/nuxt/*'],
policies: undefined,
reportOnly: false,
test: true
})
})
test('should fallback to server target', () => {
const { target } = getNuxtConfig({ target: 0 })
expect(target).toEqual('server')
})
test('should check unknown target', () => {
const { target } = getNuxtConfig({ target: 'test' })
expect(consola.warn).toHaveBeenCalledWith('Unknown target: test. Falling back to server')
expect(target).toEqual('server')
})
test('should check unknown mode', () => {
const { build, render } = getNuxtConfig({ mode: 'test' })
expect(consola.warn).toHaveBeenCalledWith('Unknown mode: test. Falling back to universal')
expect(build.ssr).toEqual(true)
expect(render.ssr).toEqual(true)
})
test('should add appear true in pageTransition when no ssr', () => {
const { pageTransition } = getNuxtConfig({ render: { ssr: false } })
expect(pageTransition.appear).toEqual(true)
})
test('should return 200.html as default generate.fallback', () => {
const { generate: { fallback } } = getNuxtConfig({})
expect(fallback).toEqual('200.html')
})
test('should return 404.html when generate.fallback is true', () => {
const { generate: { fallback } } = getNuxtConfig({ generate: { fallback: true } })
expect(fallback).toEqual('404.html')
})
test('should return fallback html when generate.fallback is string', () => {
const { generate: { fallback } } = getNuxtConfig({ generate: { fallback: 'fallback.html' } })
expect(fallback).toEqual('fallback.html')
})
test('should disable parallel if extractCSS is enabled', () => {
const { build: { parallel } } = getNuxtConfig({ build: { extractCSS: true, parallel: true } })
expect(parallel).toEqual(false)
expect(consola.warn).toHaveBeenCalledWith('extractCSS cannot work with parallel build due to limited work pool in thread-loader')
})
describe('config: router dir', () => {
test('should transform middleware to array', () => {
const { router: { middleware } } = getNuxtConfig({ router: { middleware: 'midd' } })
expect(middleware).toEqual(['midd'])
})
test('should set _routerBaseSpecified when base is specified', () => {
const { _routerBaseSpecified } = getNuxtConfig({ router: { base: '/test' } })
expect(_routerBaseSpecified).toEqual(true)
})
})
describe('config: options dir', () => {
test('should support custom root dir', () => {
const { rootDir } = getNuxtConfig({
rootDir: 'root'
})
expect(rootDir).toEqual(path.resolve('root'))
})
test('should support custom src dir', () => {
const { srcDir } = getNuxtConfig({
rootDir: 'root',
srcDir: 'src'
})
expect(srcDir).toEqual(path.resolve('root', 'src'))
})
test('should support custom generate dir', () => {
const { generate: { dir } } = getNuxtConfig({
rootDir: 'root',
generate: { dir: 'generate' }
})
expect(dir).toEqual(path.resolve('root', 'generate'))
})
})
describe('config: options template', () => {
test('should use default appTemplatePath', () => {
const { appTemplatePath } = getNuxtConfig({})
expect(appTemplatePath).toEqual(path.resolve('.nuxt', 'views', 'app.template.html'))
})
test('should use custom appTemplatePath', () => {
const { appTemplatePath } = getNuxtConfig({ appTemplatePath: 'templates' })
expect(appTemplatePath).toEqual(path.resolve('templates'))
})
test('should use custom app.html', () => {
const { appTemplatePath } = getNuxtConfig({ rootDir: path.resolve(__dirname, 'fixtures') })
expect(appTemplatePath).toEqual(path.resolve(__dirname, 'fixtures', 'app.html'))
})
})
describe('config: options publicPath', () => {
test('should fallback to default when publicPath is falsy', () => {
const { build: { publicPath } } = getNuxtConfig({ build: { publicPath: false } })
expect(publicPath).toEqual('/_nuxt/')
})
test('should append slash in publicPath', () => {
const { build: { publicPath } } = getNuxtConfig({ build: { publicPath: '/nuxt_public' } })
expect(publicPath).toEqual('/nuxt_public/')
})
test('should ignore url publicPath in dev', () => {
const { build: { publicPath } } = getNuxtConfig({ dev: true, build: { publicPath: 'http://nuxt_public' } })
expect(publicPath).toEqual('/_nuxt/')
})
})
describe('config: options babel', () => {
test('should replace and deprecate @nuxtjs/babel-preset-app', () => {
const { build: { babel } } = getNuxtConfig({
build: { babel: { presets: ['@nuxtjs/babel-preset-app'] } }
})
expect(consola.warn).toHaveBeenCalledWith('@nuxtjs/babel-preset-app has been deprecated, please use @nuxt/babel-preset-app.')
expect(babel).toEqual({
configFile: false,
babelrc: false,
cacheDirectory: false,
presets: ['@nuxt/babel-preset-app']
})
})
test('should support options in babel presets', () => {
const { build: { babel } } = getNuxtConfig({
build: { babel: { presets: [['@nuxt/babel-preset-app', { test: true }]] } }
})
expect(babel).toEqual({
configFile: false,
babelrc: false,
cacheDirectory: false,
presets: [['@nuxt/babel-preset-app', { test: true }]]
})
})
})
describe('config: options deprecated', () => {
test('should deprecate render.gzip', () => {
getNuxtConfig({ render: { gzip: true } })
expect(consola.warn).toHaveBeenCalledWith('render.gzip is deprecated and will be removed in a future version! Please switch to render.compressor')
})
test('should deprecate build.vendor', () => {
getNuxtConfig({ build: { vendor: ['lodash'] } })
expect(consola.warn).toHaveBeenCalledWith('vendor has been deprecated due to webpack4 optimization')
})
test('should deprecate devModules', () => {
const config = getNuxtConfig({ devModules: ['foo'], buildModules: ['bar'] })
expect(consola.warn).toHaveBeenCalledWith('`devModules` has been renamed to `buildModules` and will be removed in Nuxt 3.')
expect(config.devModules).toBe(undefined)
expect(config.buildModules).toEqual(['bar', 'foo'])
})
test('should deprecate build.extractCSS.allChunks', () => {
getNuxtConfig({ build: { extractCSS: { allChunks: true } } })
expect(consola.warn).toHaveBeenCalledWith('build.extractCSS.allChunks has no effect from v2.0.0. Please use build.optimization.splitChunks settings instead.')
})
test('should deprecate build.crossorigin', () => {
getNuxtConfig({ build: { crossorigin: 'use-credentials' } })
expect(consola.warn).toHaveBeenCalledWith('Using `build.crossorigin` is deprecated and will be removed in Nuxt 3. Please use `render.crossorigin` instead.')
})
})
})
describe('config: serverMiddleware', () => {
test('should transform serverMiddleware hash', () => {
const serverMiddleware = {
'/resource': (req, res, next) => {
}
}
const config = getNuxtConfig({ serverMiddleware })
expect(config.serverMiddleware[0].path).toBe('/resource')
expect(config.serverMiddleware[0].handler).toBe(serverMiddleware['/resource'])
})
})
describe('config: router', () => {
test('should sanitize router.base', () => {
const config = getNuxtConfig({ router: { base: '/foo' } })
expect(config.router.base).toBe('/foo/')
})
})