fix(vite): swap <link> style on dev ssr (#1712)

This commit is contained in:
Anthony Fu 2021-11-05 16:55:53 +08:00 committed by GitHub
parent 91b428eeea
commit 85d173d653
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 30 additions and 2 deletions

View File

@ -3,6 +3,7 @@ import * as vite from 'vite'
import { createVuePlugin } from 'vite-plugin-vue2' import { createVuePlugin } from 'vite-plugin-vue2'
import PluginLegacy from '@vitejs/plugin-legacy' import PluginLegacy from '@vitejs/plugin-legacy'
import consola from 'consola' import consola from 'consola'
import { devStyleSSRPlugin } from '../../../vite/src/plugins/dev-ssr-css'
import { jsxPlugin } from './plugins/jsx' import { jsxPlugin } from './plugins/jsx'
import { ViteBuildContext, ViteOptions } from './types' import { ViteBuildContext, ViteOptions } from './types'
@ -38,7 +39,8 @@ export async function buildClient (ctx: ViteBuildContext) {
plugins: [ plugins: [
jsxPlugin(), jsxPlugin(),
createVuePlugin(ctx.config.vue), createVuePlugin(ctx.config.vue),
PluginLegacy() PluginLegacy(),
devStyleSSRPlugin(ctx.nuxt.options.rootDir)
], ],
server: { server: {
middlewareMode: true middlewareMode: true

View File

@ -11,6 +11,7 @@ import { cacheDirPlugin } from './plugins/cache-dir'
import { wpfs } from './utils/wpfs' import { wpfs } from './utils/wpfs'
import type { ViteBuildContext, ViteOptions } from './vite' import type { ViteBuildContext, ViteOptions } from './vite'
import { writeManifest } from './manifest' import { writeManifest } from './manifest'
import { devStyleSSRPlugin } from './plugins/dev-ssr-css'
export async function buildClient (ctx: ViteBuildContext) { export async function buildClient (ctx: ViteBuildContext) {
const clientConfig: vite.InlineConfig = vite.mergeConfig(ctx.config, { const clientConfig: vite.InlineConfig = vite.mergeConfig(ctx.config, {
@ -38,7 +39,8 @@ export async function buildClient (ctx: ViteBuildContext) {
plugins: [ plugins: [
cacheDirPlugin(ctx.nuxt.options.rootDir, 'client'), cacheDirPlugin(ctx.nuxt.options.rootDir, 'client'),
vuePlugin(ctx.config.vue), vuePlugin(ctx.config.vue),
viteJsxPlugin() viteJsxPlugin(),
devStyleSSRPlugin(ctx.nuxt.options.rootDir)
], ],
server: { server: {
middlewareMode: true middlewareMode: true

View File

@ -0,0 +1,24 @@
import { Plugin } from 'vite'
import { isCSS } from '../utils'
export function devStyleSSRPlugin (rootDir: string): Plugin {
return {
name: 'nuxt:dev-style-ssr',
apply: 'serve',
enforce: 'post',
transform (code, id) {
if (!isCSS(id) || !code.includes('import.meta.hot')) {
return
}
let moduleId = id
if (moduleId.startsWith(rootDir)) {
moduleId = moduleId.slice(rootDir.length)
}
// When dev `<style>` is injected, remove the `<link>` styles from manifest
// TODO: Use `app.assetsPath` or unique hash
return code + `\ndocument.querySelector(\`link[href="/_nuxt${moduleId}"]\`).forEach(i=>i.remove())`
}
}
}