2021-04-29 11:51:54 +00:00
|
|
|
import * as vite from 'vite'
|
2021-07-21 20:05:22 +00:00
|
|
|
import { resolve } from 'upath'
|
|
|
|
import { mkdirp, writeFile } from 'fs-extra'
|
2021-04-29 11:51:54 +00:00
|
|
|
import vitePlugin from '@vitejs/plugin-vue'
|
|
|
|
import { cacheDirPlugin } from './plugins/cache-dir'
|
|
|
|
import { replace } from './plugins/replace'
|
|
|
|
import { ViteBuildContext, ViteOptions } from './vite'
|
2021-06-16 12:42:58 +00:00
|
|
|
import { transformNuxtSetup } from './plugins/transformSetup'
|
2021-04-29 11:51:54 +00:00
|
|
|
|
|
|
|
export async function buildClient (ctx: ViteBuildContext) {
|
|
|
|
const clientConfig: vite.InlineConfig = vite.mergeConfig(ctx.config, {
|
|
|
|
define: {
|
|
|
|
'process.server': false,
|
|
|
|
'process.client': true,
|
|
|
|
'module.hot': false,
|
|
|
|
global: 'globalThis'
|
|
|
|
},
|
2021-07-23 14:58:38 +00:00
|
|
|
resolve: {
|
|
|
|
alias: {
|
|
|
|
'#build/plugins': resolve(ctx.nuxt.options.buildDir, 'plugins/client')
|
|
|
|
}
|
|
|
|
},
|
2021-04-29 11:51:54 +00:00
|
|
|
build: {
|
|
|
|
outDir: 'dist/client',
|
2021-07-15 10:18:34 +00:00
|
|
|
assetsDir: '.'
|
2021-04-29 11:51:54 +00:00
|
|
|
},
|
|
|
|
plugins: [
|
|
|
|
replace({ 'process.env': 'import.meta.env' }),
|
|
|
|
cacheDirPlugin(ctx.nuxt.options.rootDir, 'client'),
|
2021-06-16 12:42:58 +00:00
|
|
|
vitePlugin(ctx.config.vue),
|
|
|
|
transformNuxtSetup()
|
2021-04-29 11:51:54 +00:00
|
|
|
],
|
|
|
|
server: {
|
|
|
|
middlewareMode: true
|
|
|
|
}
|
|
|
|
} as ViteOptions)
|
|
|
|
|
|
|
|
await ctx.nuxt.callHook('vite:extendConfig', clientConfig, { isClient: true, isServer: false })
|
|
|
|
|
2021-07-21 20:05:22 +00:00
|
|
|
const clientManifest = {
|
|
|
|
publicPath: ctx.nuxt.options.build.publicPath,
|
|
|
|
all: [],
|
|
|
|
initial: [ctx.nuxt.options.dev && '@vite/client', 'entry.mjs'].filter(Boolean),
|
|
|
|
async: [],
|
|
|
|
modules: {}
|
|
|
|
}
|
|
|
|
|
|
|
|
const serverDist = resolve(ctx.nuxt.options.buildDir, 'dist/server')
|
|
|
|
await mkdirp(serverDist)
|
|
|
|
await writeFile(resolve(serverDist, 'client.manifest.json'), JSON.stringify(clientManifest, null, 2), 'utf8')
|
|
|
|
await writeFile(resolve(serverDist, 'client.manifest.mjs'), 'export default ' + JSON.stringify(clientManifest, null, 2), 'utf8')
|
|
|
|
|
2021-04-29 11:51:54 +00:00
|
|
|
const viteServer = await vite.createServer(clientConfig)
|
|
|
|
await ctx.nuxt.callHook('vite:serverCreated', viteServer)
|
|
|
|
|
|
|
|
const viteMiddleware = (req, res, next) => {
|
|
|
|
// Workaround: vite devmiddleware modifies req.url
|
|
|
|
const originalURL = req.url
|
|
|
|
viteServer.middlewares.handle(req, res, (err) => {
|
|
|
|
req.url = originalURL
|
|
|
|
next(err)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
await ctx.nuxt.callHook('server:devMiddleware', viteMiddleware)
|
|
|
|
|
|
|
|
ctx.nuxt.hook('close', async () => {
|
|
|
|
await viteServer.close()
|
|
|
|
})
|
|
|
|
}
|