Nuxt/packages/builder/test/builder.build.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

285 lines
11 KiB
JavaScript

import path from 'path'
import consola from 'consola'
import fsExtra from 'fs-extra'
import semver from 'semver'
import { r, waitFor } from '@nuxt/utils'
import { BundleBuilder } from '@nuxt/webpack'
import Builder from '../src/builder'
import { createNuxt } from './__utils__'
jest.mock('fs-extra')
jest.mock('semver/functions/satisfies')
jest.mock('hash-sum', () => src => `hash(${src})`)
jest.mock('@nuxt/utils')
jest.mock('../src/ignore')
jest.mock('@nuxt/webpack')
describe('builder: builder build', () => {
beforeAll(() => {
jest.spyOn(path, 'join').mockImplementation((...args) => `join(${args.join(', ')})`)
})
afterAll(() => {
path.join.mockRestore()
})
beforeEach(() => {
jest.clearAllMocks()
})
test('should build all resources', async () => {
const nuxt = createNuxt()
nuxt.options.srcDir = '/var/nuxt/src'
nuxt.options.buildDir = '/var/nuxt/build'
nuxt.options.dir = { pages: '/var/nuxt/src/pages' }
nuxt.options.build.template = { dir: '/var/nuxt/src/template' }
nuxt.options.build.createRoutes = jest.fn()
nuxt.options.render = { ssr: true }
const bundleBuilder = { build: jest.fn() }
const builder = new Builder(nuxt, bundleBuilder)
builder.validatePages = jest.fn()
builder.validateTemplate = jest.fn()
builder.generateRoutesAndFiles = jest.fn()
builder.resolvePlugins = jest.fn()
r.mockImplementation((dir, src) => `r(${dir})`)
const buildReturn = await builder.build()
expect(consola.info).toBeCalledTimes(3)
expect(consola.info).toBeCalledWith('Production build')
expect(nuxt.ready).toBeCalledTimes(1)
expect(nuxt.callHook).toBeCalledTimes(3)
expect(nuxt.callHook).nthCalledWith(1, 'build:before', builder, nuxt.options.build)
expect(nuxt.callHook).nthCalledWith(2, 'builder:prepared', builder, nuxt.options.build)
expect(builder.validatePages).toBeCalledTimes(1)
expect(builder.validateTemplate).toBeCalledTimes(1)
expect(consola.success).toBeCalledTimes(1)
expect(consola.success).toBeCalledWith('Builder initialized')
expect(consola.debug).toBeCalledTimes(1)
expect(consola.debug).toBeCalledWith('App root: /var/nuxt/src')
expect(fsExtra.remove).toBeCalledTimes(1)
expect(fsExtra.remove).toBeCalledWith('r(/var/nuxt/build)')
expect(fsExtra.mkdirp).toBeCalledTimes(3)
expect(fsExtra.mkdirp).nthCalledWith(1, 'r(/var/nuxt/build)')
expect(fsExtra.mkdirp).nthCalledWith(2, 'r(/var/nuxt/build)')
expect(fsExtra.mkdirp).nthCalledWith(3, 'r(/var/nuxt/build)')
expect(r).toBeCalledTimes(4)
expect(r).nthCalledWith(1, '/var/nuxt/build')
expect(r).nthCalledWith(2, '/var/nuxt/build', 'components')
expect(r).nthCalledWith(3, '/var/nuxt/build', 'dist', 'client')
expect(r).nthCalledWith(4, '/var/nuxt/build', 'dist', 'server')
expect(builder.generateRoutesAndFiles).toBeCalledTimes(1)
expect(nuxt.options.build.watch).toEqual(['/var/nuxt/src/template/**/*.{vue,js}'])
expect(builder.resolvePlugins).toBeCalledTimes(1)
expect(bundleBuilder.build).toBeCalledTimes(1)
expect(builder._buildStatus).toEqual(2)
expect(nuxt.callHook).nthCalledWith(3, 'build:done', builder)
expect(buildReturn).toBe(builder)
})
test('should prevent duplicate build in dev mode', async () => {
const nuxt = createNuxt()
nuxt.options.dev = true
const builder = new Builder(nuxt, BundleBuilder)
builder._buildStatus = 3
waitFor.mockImplementationOnce(() => {
builder.build = jest.fn(() => 'calling build')
})
const buildReturn = await builder.build()
expect(nuxt.ready).not.toBeCalled()
expect(waitFor).toBeCalledTimes(1)
expect(waitFor).toBeCalledWith(1000)
expect(builder.build).toBeCalledTimes(1)
expect(buildReturn).toBe('calling build')
})
test('should wait 1000ms and retry if building is in progress', async () => {
const nuxt = createNuxt()
nuxt.options.dev = true
const builder = new Builder(nuxt, BundleBuilder)
builder._buildStatus = 2
const buildReturn = await builder.build()
expect(nuxt.ready).not.toBeCalled()
expect(buildReturn).toBe(builder)
})
test('should build in dev mode and print dev mode building messages', async () => {
const nuxt = createNuxt()
nuxt.options.dev = true
nuxt.options.srcDir = '/var/nuxt/src'
nuxt.options.buildDir = '/var/nuxt/build'
nuxt.options.dir = { pages: '/var/nuxt/src/pages' }
nuxt.options.build.createRoutes = jest.fn()
nuxt.options.render = { ssr: true }
const bundleBuilder = { build: jest.fn() }
const builder = new Builder(nuxt, bundleBuilder)
builder.validatePages = jest.fn()
builder.validateTemplate = jest.fn()
builder.generateRoutesAndFiles = jest.fn()
builder.resolvePlugins = jest.fn()
await builder.build()
expect(consola.info).toBeCalledTimes(2)
expect(consola.info).nthCalledWith(1, 'Preparing project for development')
expect(consola.info).nthCalledWith(2, 'Initial build may take a while')
expect(fsExtra.mkdirp).toBeCalledTimes(1)
expect(fsExtra.mkdirp).toBeCalledWith('r(/var/nuxt/build)')
expect(r).toBeCalledTimes(2)
expect(r).nthCalledWith(1, '/var/nuxt/build')
expect(r).nthCalledWith(2, '/var/nuxt/build', 'components')
})
test('should throw error when validateTemplate failed', async () => {
const nuxt = createNuxt()
const builder = new Builder(nuxt, BundleBuilder)
builder.validatePages = jest.fn()
builder.validateTemplate = jest.fn(() => {
throw new Error('validate failed')
})
consola.success.mockImplementationOnce(() => {
throw new Error('exit')
})
await expect(builder.build()).rejects.toThrow('exit')
expect(builder._buildStatus).toEqual(3)
expect(consola.fatal).toBeCalledTimes(1)
expect(consola.fatal).toBeCalledWith(new Error('validate failed'))
})
test('should warn built-in page will be used if no pages dir found', async () => {
const nuxt = createNuxt()
nuxt.options.srcDir = '/var/nuxt/src'
nuxt.options.dir = { pages: '/var/nuxt/src/pages' }
const builder = new Builder(nuxt, BundleBuilder)
fsExtra.exists.mockReturnValue(false)
await builder.validatePages()
expect(builder._nuxtPages).toEqual(true)
expect(path.join).toBeCalledTimes(2)
expect(path.join).nthCalledWith(1, '/var/nuxt/src', '/var/nuxt/src/pages')
expect(path.join).nthCalledWith(2, '/var/nuxt/src', '..', '/var/nuxt/src/pages')
expect(fsExtra.exists).toBeCalledTimes(2)
expect(fsExtra.exists).nthCalledWith(1, 'join(/var/nuxt/src, /var/nuxt/src/pages)')
expect(fsExtra.exists).nthCalledWith(2, 'join(/var/nuxt/src, .., /var/nuxt/src/pages)')
expect(builder._defaultPage).toEqual(true)
expect(consola.warn).toBeCalledTimes(1)
expect(consola.warn).toBeCalledWith('No `/var/nuxt/src/pages` directory found in /var/nuxt/src. Using the default built-in page.')
})
test('should throw error if pages is found in parent dir', async () => {
const nuxt = createNuxt()
nuxt.options.srcDir = '/var/nuxt/src'
nuxt.options.dir = { pages: '/var/nuxt/src/pages' }
const builder = new Builder(nuxt, BundleBuilder)
fsExtra.exists
.mockReturnValueOnce(false)
.mockReturnValueOnce(true)
await expect(builder.validatePages()).rejects.toThrow(
'No `/var/nuxt/src/pages` directory found in /var/nuxt/src. Did you mean to run `nuxt` in the parent (`../`) directory?'
)
expect(builder._nuxtPages).toEqual(true)
expect(path.join).toBeCalledTimes(2)
expect(path.join).nthCalledWith(1, '/var/nuxt/src', '/var/nuxt/src/pages')
expect(path.join).nthCalledWith(2, '/var/nuxt/src', '..', '/var/nuxt/src/pages')
expect(fsExtra.exists).toBeCalledTimes(2)
expect(fsExtra.exists).nthCalledWith(1, 'join(/var/nuxt/src, /var/nuxt/src/pages)')
expect(fsExtra.exists).nthCalledWith(2, 'join(/var/nuxt/src, .., /var/nuxt/src/pages)')
expect(builder._defaultPage).toBeUndefined()
})
test('should pass validation if createRoutes is function', async () => {
const nuxt = createNuxt()
nuxt.options.build.createRoutes = jest.fn()
const builder = new Builder(nuxt, BundleBuilder)
await builder.validatePages()
expect(builder._nuxtPages).toEqual(false)
expect(fsExtra.exists).not.toBeCalled()
})
test('should pass validation if pages exists', async () => {
const nuxt = createNuxt()
nuxt.options.srcDir = '/var/nuxt/src'
nuxt.options.dir = { pages: '/var/nuxt/src/pages' }
const builder = new Builder(nuxt, BundleBuilder)
fsExtra.exists.mockReturnValueOnce(true)
await builder.validatePages()
expect(builder._nuxtPages).toEqual(true)
expect(path.join).toBeCalledTimes(1)
expect(path.join).toBeCalledWith('/var/nuxt/src', '/var/nuxt/src/pages')
expect(fsExtra.exists).toBeCalledTimes(1)
expect(fsExtra.exists).toBeCalledWith('join(/var/nuxt/src, /var/nuxt/src/pages)')
expect(builder._defaultPage).toBeUndefined()
})
test('should validate dependencies in template', () => {
const nuxt = createNuxt()
nuxt.options.build.template = {
dependencies: {
vue: 'latest',
nuxt: 'edge'
}
}
const builder = new Builder(nuxt, BundleBuilder)
semver.satisfies
.mockReturnValueOnce(true)
.mockReturnValueOnce(true)
nuxt.resolver.requireModule
.mockReturnValueOnce({ version: 'alpha' })
.mockReturnValueOnce({ version: 'beta' })
builder.validateTemplate()
expect(nuxt.resolver.requireModule).toBeCalledTimes(2)
expect(nuxt.resolver.requireModule).nthCalledWith(1, 'join(vue, package.json)')
expect(nuxt.resolver.requireModule).nthCalledWith(2, 'join(nuxt, package.json)')
expect(semver.satisfies).toBeCalledTimes(2)
expect(semver.satisfies).nthCalledWith(1, 'alpha', 'latest')
expect(semver.satisfies).nthCalledWith(2, 'beta', 'edge')
})
test('should warn and throw error if dependencies is not installed', () => {
const nuxt = createNuxt()
nuxt.options.build.template = {
dependencies: {
vue: 'latest',
nuxt: 'edge'
}
}
const builder = new Builder(nuxt, BundleBuilder)
semver.satisfies
.mockReturnValueOnce(false)
nuxt.resolver.requireModule
.mockReturnValueOnce({ version: 'alpha' })
.mockReturnValueOnce(undefined)
builder.validateTemplate()
expect(nuxt.resolver.requireModule).toBeCalledTimes(2)
expect(nuxt.resolver.requireModule).nthCalledWith(1, 'join(vue, package.json)')
expect(nuxt.resolver.requireModule).nthCalledWith(2, 'join(nuxt, package.json)')
expect(consola.warn).toBeCalledTimes(2)
expect(consola.warn).nthCalledWith(1, 'vue@latest is recommended but vue@alpha is installed!')
expect(consola.warn).nthCalledWith(2, 'nuxt@edge is required but not installed!')
expect(semver.satisfies).toBeCalledTimes(1)
expect(semver.satisfies).nthCalledWith(1, 'alpha', 'latest')
})
})