feat: modern build (#4231)

* feat: modern build

* refactor: use single module import for lodash

* refactor: add credit comment for modern plugin

* feat: ssr modern build

* fix: not null check for request

* fix: not null check for request.headers

* feat: add modern argument on build command

* refactor: simpilfy filenames for modern

* refactor: use packages/webpack src instead of dist in test

* test: add feature test for modern build
This commit is contained in:
Clark Du 2018-10-31 15:52:35 +00:00 committed by GitHub
parent c86dfbf43f
commit bed0714fad
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
17 changed files with 335 additions and 38 deletions

View File

@ -24,6 +24,17 @@ export default {
default: true,
description: 'Don\'t generate static version for SPA mode (useful for nuxt start)'
},
modern: {
alias: 'm',
type: 'boolean',
description: 'Build app for modern browsers',
prepare(cmd, options, argv) {
options.build = options.build || {}
if (argv.modern) {
options.build.modern = !!argv.modern
}
}
},
quiet: {
alias: 'q',
type: 'boolean',

View File

@ -7,13 +7,14 @@ export default () => ({
extractCSS: false,
cssSourceMap: undefined,
ssr: undefined,
modern: 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',
app: ({ isDev, isModern }) => isDev ? `${isModern ? 'modern-' : ''}[name].js` : '[chunkhash].js',
chunk: ({ isDev, isModern }) => isDev ? `${isModern ? 'modern-' : ''}[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]',
@ -106,7 +107,7 @@ export default () => ({
excludeAssets: [
/.map$/,
/index\..+\.html$/,
/vue-ssr-client-manifest.json/
/vue-ssr-(client|modern)-manifest.json/
]
}
})

View File

@ -0,0 +1,9 @@
{
"edge": "16",
"firefox": "60",
"chrome": "61",
"safari": "10.1",
"opera": "48",
"ios_saf": "10.3",
"and_ff": "60"
}

View File

@ -10,6 +10,7 @@
"dependencies": {
"@nuxt/common": "^2.2.0",
"@nuxtjs/devalue": "^1.0.1",
"browserslist-useragent": "^2.0.1",
"consola": "^1.4.4",
"fs-extra": "^7.0.0",
"lru-cache": "^4.1.3",

View File

@ -1,13 +1,14 @@
import path from 'path'
import crypto from 'crypto'
import fs from 'fs-extra'
import consola from 'consola'
import devalue from '@nuxtjs/devalue'
import template from 'lodash/template'
import fs from 'fs-extra'
import { createBundleRenderer } from 'vue-server-renderer'
import consola from 'consola'
import { waitFor } from '@nuxt/common'
import { matchesUA } from 'browserslist-useragent'
import { createBundleRenderer } from 'vue-server-renderer'
import ModernBrowsers from '../data/modern-browsers.json'
import SPAMetaRenderer from './spa-meta'
export default class VueRenderer {
@ -15,12 +16,19 @@ export default class VueRenderer {
this.context = context
// Will be set by createRenderer
this.bundleRenderer = null
this.spaMetaRenderer = null
this.renderer = {
ssr: null,
modern: null,
spa: null
}
this.modernBrowsers = Object.keys(ModernBrowsers)
.map(browser => `${browser} >= ${ModernBrowsers[browser]}`)
// Renderer runtime resources
Object.assign(this.context.resources, {
clientManifest: null,
modernManifest: null,
serverBundle: null,
ssrTemplate: null,
spaTemplate: null,
@ -95,7 +103,7 @@ export default class VueRenderer {
return Boolean(this.context.resources.spaTemplate)
}
return Boolean(this.bundleRenderer && this.context.resources.ssrTemplate)
return Boolean(this.renderer.ssr && this.context.resources.ssrTemplate)
}
get isResourcesAvailable() {
@ -121,7 +129,7 @@ export default class VueRenderer {
}
// Create Meta Renderer
this.spaMetaRenderer = new SPAMetaRenderer(this)
this.renderer.spa = new SPAMetaRenderer(this)
// Skip following steps if noSSR mode
if (this.noSSR) {
@ -129,19 +137,29 @@ export default class VueRenderer {
}
const hasModules = fs.existsSync(path.resolve(this.context.options.rootDir, 'node_modules'))
const rendererOptions = {
runInNewContext: false,
clientManifest: this.context.resources.clientManifest,
// for globally installed nuxt command, search dependencies in global dir
basedir: hasModules ? this.context.options.rootDir : __dirname,
...this.context.options.render.bundleRenderer
}
// Create bundle renderer for SSR
this.bundleRenderer = createBundleRenderer(
this.renderer.ssr = createBundleRenderer(
this.context.resources.serverBundle,
Object.assign(
{
clientManifest: this.context.resources.clientManifest,
runInNewContext: false,
// for globally installed nuxt command, search dependencies in global dir
basedir: hasModules ? this.context.options.rootDir : __dirname
},
this.context.options.render.bundleRenderer
)
rendererOptions
)
if (this.context.options.build.modern) {
this.renderer.modern = createBundleRenderer(
this.context.resources.serverBundle,
{
...rendererOptions,
clientManifest: this.context.resources.modernManifest
}
)
}
}
renderTemplate(ssr, opts) {
@ -178,7 +196,7 @@ export default class VueRenderer {
HEAD,
BODY_SCRIPTS,
getPreloadFiles
} = await this.spaMetaRenderer.render(context)
} = await this.renderer.spa.render(context)
const APP =
`<div id="${this.context.globals.id}">${this.context.resources.loadingHTML}</div>` + BODY_SCRIPTS
@ -206,8 +224,20 @@ export default class VueRenderer {
return { html, getPreloadFiles }
}
const { req } = context
const ua = req && req.headers && req.headers['user-agent']
const isModernBrowser = this.renderer.modern && ua && matchesUA(ua, {
allowHigherVersions: true,
browsers: this.modernBrowsers
})
let APP
// Call renderToString from the bundleRenderer and generate the HTML (will update the context as well)
let APP = await this.bundleRenderer.renderToString(context)
if (isModernBrowser) {
APP = await this.renderer.modern.renderToString(context)
} else {
APP = await this.renderer.ssr.renderToString(context)
}
if (!context.nuxt.serverRendered) {
APP = `<div id="${this.context.globals.id}"></div>`
@ -277,6 +307,11 @@ export default class VueRenderer {
fileName: 'vue-ssr-client-manifest.json',
transform: JSON.parse
},
{
key: 'modernManifest',
fileName: 'vue-ssr-modern-manifest.json',
transform: JSON.parse
},
{
key: 'serverBundle',
fileName: 'server-bundle.json',

View File

@ -14,7 +14,7 @@ import {
wrapArray
} from '@nuxt/common'
import { ClientConfig, ServerConfig, PerfLoader } from './config'
import { ClientConfig, ModernConfig, ServerConfig, PerfLoader } from './config'
const glob = pify(Glob)
@ -45,6 +45,13 @@ export class WebpackBuilder {
const clientConfig = new ClientConfig(this).config()
compilersOptions.push(clientConfig)
// Modern
let modernConfig
if (options.build.modern) {
modernConfig = new ModernConfig(this).config()
compilersOptions.push(modernConfig)
}
// Server
let serverConfig = null
if (options.build.ssr) {
@ -63,6 +70,11 @@ export class WebpackBuilder {
// Alias to noop for ssr:false plugins
serverConfig.resolve.alias[p.name] = p.ssr ? p.src : './empty.js'
}
// Modern config
if (modernConfig && !modernConfig.resolve.alias[p.name]) {
modernConfig.resolve.alias[p.name] = p.src
}
}
// Check styleResource existence

View File

@ -17,6 +17,7 @@ export default class WebpackBaseConfig {
constructor(builder, options) {
this.name = options.name
this.isServer = options.isServer
this.isModern = options.isModern
this.builder = builder
this.nuxt = builder.context.nuxt
this.isStatic = builder.context.isStatic
@ -25,11 +26,20 @@ export default class WebpackBaseConfig {
this.loaders = this.options.build.loaders
}
get colors() {
return {
client: 'green',
server: 'orange',
modern: 'blue'
}
}
get nuxtEnv() {
return {
isDev: this.options.dev,
isServer: this.isServer,
isClient: !this.isServer
isClient: !this.isServer,
isModern: !!this.isModern
}
}
@ -249,8 +259,8 @@ export default class WebpackBaseConfig {
// Build progress indicator
plugins.push(new WebpackBar({
profile: this.options.build.profile,
name: this.isServer ? 'server' : 'client',
color: this.isServer ? 'orange' : 'green',
name: this.name,
color: this.colors[this.name],
compiledIn: false,
done: (states) => {
if (this.options.dev) {

View File

@ -6,19 +6,20 @@ import TerserWebpackPlugin from 'terser-webpack-plugin'
import OptimizeCSSAssetsPlugin from 'optimize-css-assets-webpack-plugin'
import FriendlyErrorsWebpackPlugin from '@nuxtjs/friendly-errors-webpack-plugin'
import ModernModePlugin from './plugins/vue/modern'
import VueSSRClientPlugin from './plugins/vue/client'
import WebpackBaseConfig from './base'
export default class WebpackClientConfig extends WebpackBaseConfig {
constructor(builder) {
super(builder, { name: 'client', isServer: false })
constructor(builder, options) {
super(builder, options || { name: 'client', isServer: false })
}
getFileName(...args) {
if (this.options.build.analyze) {
const key = args[0]
if (['app', 'chunk'].includes(key)) {
return '[name].js'
return `${this.name === 'modern' ? 'modern-' : ''}[name].js`
}
}
return super.getFileName(...args)
@ -77,7 +78,7 @@ export default class WebpackClientConfig extends WebpackBaseConfig {
chunksSortMode: 'dependency'
}),
new VueSSRClientPlugin({
filename: '../server/vue-ssr-client-manifest.json'
filename: `../server/vue-ssr-${this.name}-manifest.json`
}),
new webpack.DefinePlugin(this.env())
)
@ -97,11 +98,18 @@ export default class WebpackClientConfig extends WebpackBaseConfig {
defaultSizes: 'gzip',
generateStatsFile: true,
openAnalyzer: !this.options.build.quiet,
reportFilename: path.resolve(statsDir, 'client.html'),
statsFilename: path.resolve(statsDir, 'client.json')
reportFilename: path.resolve(statsDir, `${this.name}.html`),
statsFilename: path.resolve(statsDir, `${this.name}.json`)
}, this.options.build.analyze)))
}
if (this.options.build.modern) {
plugins.push(new ModernModePlugin({
targetDir: path.resolve(this.options.buildDir, 'dist', 'client'),
isModernBuild: this.name === 'modern'
}))
}
return plugins
}

View File

@ -1,3 +1,4 @@
export { default as ClientConfig } from './client'
export { default as ModernConfig } from './modern'
export { default as ServerConfig } from './server'
export { default as PerfLoader } from './utils/perf-loader'

View File

@ -0,0 +1,23 @@
import clone from 'lodash/clone'
import WebpackClientConfig from './client'
export default class WebpackModernConfig extends WebpackClientConfig {
constructor(builder) {
super(builder, { name: 'modern', isServer: false, isModern: true })
}
getBabelOptions() {
const options = clone(this.options.build.babel)
options.presets = [
[
require.resolve('@nuxt/babel-preset-app'),
{
modern: true
}
]
]
return options
}
}

View File

@ -0,0 +1,96 @@
/*
** This plugin is inspired by @vue/cli-service ModernModePlugin
** https://github.com/vuejs/vue-cli/blob/dev/packages/@vue/cli-service/lib/webpack/ModernModePlugin.js
*/
import path from 'path'
import fs from 'fs-extra'
// https://gist.github.com/samthor/64b114e4a4f539915a95b91ffd340acc
const safariFix = `!function(){var e=document,t=e.createElement("script");if(!("noModule"in t)&&"onbeforeload"in t){var n=!1;e.addEventListener("beforeload",function(e){if(e.target===t)n=!0;else if(!e.target.hasAttribute("nomodule")||!n)return;e.preventDefault()},!0),t.type="module",t.src=".",e.head.appendChild(t),t.remove()}}();`
class ModernModePlugin {
constructor({ targetDir, isModernBuild }) {
this.targetDir = targetDir
this.isModernBuild = isModernBuild
}
apply(compiler) {
if (!this.isModernBuild) {
this.applyLegacy(compiler)
} else {
this.applyModern(compiler)
}
}
applyLegacy(compiler) {
const ID = `nuxt-legacy-bundle`
compiler.hooks.compilation.tap(ID, (compilation) => {
// For html-webpack-plugin 4.0
// HtmlWebpackPlugin.getHooks(compilation).alterAssetTags.tapAsync(ID, async (data, cb) => {
compilation.hooks.htmlWebpackPluginAlterAssetTags.tapAsync(ID, async (data, cb) => {
// get stats, write to disk
await fs.ensureDir(this.targetDir)
const htmlName = path.basename(data.plugin.options.filename)
// Watch out for output files in sub directories
const htmlPath = path.dirname(data.plugin.options.filename)
const tempFilename = path.join(this.targetDir, htmlPath, `legacy-assets-${htmlName}.json`)
await fs.mkdirp(path.dirname(tempFilename))
await fs.writeFile(tempFilename, JSON.stringify(data.body))
cb()
})
})
}
applyModern(compiler) {
const ID = `nuxt-modern-bundle`
compiler.hooks.compilation.tap(ID, (compilation) => {
// For html-webpack-plugin 4.0
// HtmlWebpackPlugin.getHooks(compilation).alterAssetTags.tapAsync(ID, async (data, cb) => {
compilation.hooks.htmlWebpackPluginAlterAssetTags.tapAsync(ID, async (data, cb) => {
// use <script type="module"> for modern assets
data.body.forEach((tag) => {
if (tag.tagName === 'script' && tag.attributes) {
tag.attributes.type = 'module'
}
})
// use <link rel="modulepreload"> instead of <link rel="preload">
// for modern assets
data.head.forEach((tag) => {
if (tag.tagName === 'link' &&
tag.attributes.rel === 'preload' &&
tag.attributes.as === 'script') {
tag.attributes.rel = 'modulepreload'
}
})
// inject Safari 10 nomodule fix
data.body.push({
tagName: 'script',
closeTag: true,
innerHTML: safariFix
})
// inject links for legacy assets as <script nomodule>
const htmlName = path.basename(data.plugin.options.filename)
// Watch out for output files in sub directories
const htmlPath = path.dirname(data.plugin.options.filename)
const tempFilename = path.join(this.targetDir, htmlPath, `legacy-assets-${htmlName}.json`)
const legacyAssets = JSON.parse(await fs.readFile(tempFilename, 'utf-8'))
.filter(a => a.tagName === 'script' && a.attributes)
legacyAssets.forEach(a => (a.attributes.nomodule = ''))
data.body.push(...legacyAssets)
await fs.remove(tempFilename)
cb()
})
compilation.hooks.htmlWebpackPluginAfterHtmlProcessing.tap(ID, (data) => {
data.html = data.html.replace(/\snomodule="">/g, ' nomodule>')
})
})
}
}
ModernModePlugin.safariFix = safariFix
export default ModernModePlugin

3
test/fixtures/modern/modern.test.js vendored Normal file
View File

@ -0,0 +1,3 @@
import { buildFixture } from '../../utils/build'
buildFixture('modern')

13
test/fixtures/modern/nuxt.config.js vendored Normal file
View File

@ -0,0 +1,13 @@
export default {
build: {
modern: true,
filenames: {
app: ({ isModern }) => {
return `${isModern ? 'modern-' : ''}[name].js`
},
chunk: ({ isModern }) => {
return `${isModern ? 'modern-' : ''}[name].js`
}
}
}
}

18
test/fixtures/modern/pages/index.vue vendored Normal file
View File

@ -0,0 +1,18 @@
<template>
<h1>Index page</h1>
</template>
<script>
export default {
test() {
const test = {
build: true,
test: true,
arrow: () => { return 'build test' }
}
return {
test
}
}
}
</script>

39
test/unit/modern.test.js Normal file
View File

@ -0,0 +1,39 @@
import { loadFixture, getPort, Nuxt, rp } from '../utils'
let nuxt, port
const url = route => 'http://localhost:' + port + route
describe('modern build', () => {
beforeAll(async () => {
const options = await loadFixture('modern')
nuxt = new Nuxt(options)
port = await getPort()
await nuxt.server.listen(port, 'localhost')
})
test('should use legacy resources by default', async () => {
const response = await rp(url('/'))
expect(response).toContain('/_nuxt/app.js')
expect(response).toContain('/_nuxt/commons.app.js')
})
test('should use modern resources for modern resources', async () => {
const response = await rp(url('/'), {
headers: {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36'
}
})
expect(response).toContain('/_nuxt/modern-app.js')
expect(response).toContain('/_nuxt/modern-commons.app.js')
})
test('should include es6 syntax in modern resources', async () => {
const response = await rp(url('/_nuxt/modern-app.js'))
expect(response).toContain('arrow:()=>"build test"')
})
test('should not include es6 syntax in normal resources', async () => {
const response = await rp(url('/_nuxt/app.js'))
expect(response).not.toContain('arrow:()=>"build test"')
})
})

View File

@ -1,4 +1,4 @@
import { loadFixture, Nuxt, Builder, listPaths, equalOrStartsWith } from './index'
import { loadFixture, Nuxt, Builder, BundleBuilder, listPaths, equalOrStartsWith } from './index'
export const buildFixture = function (fixture, callback, hooks = []) {
const pathsBefore = {}
@ -16,7 +16,7 @@ export const buildFixture = function (fixture, callback, hooks = []) {
const buildDone = jest.fn()
hooks.forEach(([hook, fn]) => nuxt.hook(hook, fn))
nuxt.hook('build:done', buildDone)
const builder = await new Builder(nuxt).build()
const builder = await new Builder(nuxt, BundleBuilder).build()
// 2: BUILD_DONE
expect(builder._buildStatus).toBe(2)
expect(buildDone).toHaveBeenCalledTimes(1)

View File

@ -2419,6 +2419,15 @@ browserify-zlib@^0.2.0:
dependencies:
pako "~1.0.5"
browserslist-useragent@^2.0.1:
version "2.0.1"
resolved "https://registry.npmjs.org/browserslist-useragent/-/browserslist-useragent-2.0.1.tgz#ea5f706bc426c5fb2b5adf97cde7c1aed0864d0f"
integrity sha1-6l9wa8QmxfsrWt+XzefBrtCGTQ8=
dependencies:
browserslist "^4.0.1"
semver "^5.4.1"
useragent "^2.2.1"
browserslist@^4.0.0, browserslist@^4.1.0:
version "4.2.1"
resolved "https://registry.npmjs.org/browserslist/-/browserslist-4.2.1.tgz#257a24c879d1cd4016348eee5c25de683260b21d"
@ -2428,7 +2437,7 @@ browserslist@^4.0.0, browserslist@^4.1.0:
electron-to-chromium "^1.3.79"
node-releases "^1.0.0-alpha.14"
browserslist@^4.3.3, browserslist@^4.3.4:
browserslist@^4.0.1, browserslist@^4.3.3, browserslist@^4.3.4:
version "4.3.4"
resolved "https://registry.npmjs.org/browserslist/-/browserslist-4.3.4.tgz#4477b737db6a1b07077275b24791e680d4300425"
integrity sha512-u5iz+ijIMUlmV8blX82VGFrB9ecnUg5qEt55CMZ/YJEhha+d8qpBfOFuutJ6F/VKRXjZoD33b6uvarpPxcl3RA==
@ -6768,7 +6777,7 @@ lower-case@^1.1.1:
resolved "https://registry.npmjs.org/lower-case/-/lower-case-1.1.4.tgz#9a2cabd1b9e8e0ae993a4bf7d5875c39c42e8eac"
integrity sha1-miyr0bno4K6ZOkv31YdcOcQujqw=
lru-cache@^4.0.1, lru-cache@^4.1.1, lru-cache@^4.1.2, lru-cache@^4.1.3:
lru-cache@4.1.x, lru-cache@^4.0.1, lru-cache@^4.1.1, lru-cache@^4.1.2, lru-cache@^4.1.3:
version "4.1.3"
resolved "https://registry.npmjs.org/lru-cache/-/lru-cache-4.1.3.tgz#a1175cf3496dfc8436c156c334b4955992bce69c"
integrity sha512-fFEhvcgzuIoJVUF8fYr5KR0YqxD238zgObTps31YdADwPPAp82a4M8TrckkWyx7ekNlf9aBcVn81cFwwXngrJA==
@ -10468,7 +10477,7 @@ timsort@^0.3.0:
resolved "https://registry.npmjs.org/timsort/-/timsort-0.3.0.tgz#405411a8e7e6339fe64db9a234de11dc31e02bd4"
integrity sha1-QFQRqOfmM5/mTbmiNN4R3DHgK9Q=
tmp@^0.0.33:
tmp@0.0.x, tmp@^0.0.33:
version "0.0.33"
resolved "https://registry.npmjs.org/tmp/-/tmp-0.0.33.tgz#6d34335889768d21b2bcda0aa277ced3b1bfadf9"
integrity sha512-jRCJlojKnZ3addtTOjdIqoRuPEKBvNXcGYqzO6zWZX8KfKEpnGY5jfggJQ3EjKuu8D4bJRr0y+cYJFmYbImXGw==
@ -10806,6 +10815,14 @@ use@^3.1.0:
resolved "https://registry.npmjs.org/use/-/use-3.1.1.tgz#d50c8cac79a19fbc20f2911f56eb973f4e10070f"
integrity sha512-cwESVXlO3url9YWlFW/TA9cshCEhtu7IKJ/p5soJ/gGpj7vbvFrAY/eIioQ6Dw23KjZhYgiIo8HOs1nQ2vr/oQ==
useragent@^2.2.1:
version "2.3.0"
resolved "https://registry.npmjs.org/useragent/-/useragent-2.3.0.tgz#217f943ad540cb2128658ab23fc960f6a88c9972"
integrity sha512-4AoH4pxuSvHCjqLO04sU6U/uE65BYza8l/KKBS0b0hnUPWi+cQ2BpeTEwejCSx9SPV5/U03nniDTrWx5NrmKdw==
dependencies:
lru-cache "4.1.x"
tmp "0.0.x"
util-deprecate@~1.0.1:
version "1.0.2"
resolved "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz#450d4dc9fa70de732762fbd2d4a28981419a0ccf"