Skip to content
This repository has been archived by the owner on Apr 6, 2023. It is now read-only.

Commit

Permalink
feat(vite)!: upgrade vite to v3 (#5398)
Browse files Browse the repository at this point in the history
  • Loading branch information
danielroe committed Jul 21, 2022
1 parent 2e794e7 commit fa8b0f7
Show file tree
Hide file tree
Showing 19 changed files with 178 additions and 235 deletions.
2 changes: 1 addition & 1 deletion package.json
Expand Up @@ -42,7 +42,7 @@
"nuxi": "link:./packages/nuxi",
"nuxt": "link:./packages/nuxt",
"nuxt3": "link:./packages/nuxt",
"vite": "^2.9.14",
"vite": "~3.0.0",
"unbuild": "^0.7.6"
},
"devDependencies": {
Expand Down
4 changes: 2 additions & 2 deletions packages/nuxt/src/components/loader.ts
Expand Up @@ -31,8 +31,8 @@ export const loaderPlugin = createUnplugin((options: LoaderOptions) => {
const { pathname, search } = parseURL(decodeURIComponent(pathToFileURL(id).href))
const query = parseQuery(search)
// we only transform render functions
// from `type=template` (in Webpack) and bare `.vue` file (in Vite)
return pathname.endsWith('.vue') && (query.type === 'template' || !!query.macro || !search)
// from `type=template` (in Webpack), bare `.vue` file and setup=true (Vite 2/3)
return pathname.endsWith('.vue') && (query.type === 'template' || !!query.macro || !!query.setup || !search)
},
transform (code, id) {
const components = options.getComponents()
Expand Down
5 changes: 1 addition & 4 deletions packages/nuxt/src/core/nitro.ts
Expand Up @@ -41,10 +41,7 @@ export async function initNitro (nuxt: Nuxt) {
generateTsConfig: false
},
publicAssets: [
{
baseURL: nuxt.options.app.buildAssetsDir,
dir: resolve(nuxt.options.buildDir, 'dist/client')
},
{ dir: resolve(nuxt.options.buildDir, 'dist/client') },
...nuxt.options._layers
.map(layer => join(layer.config.srcDir, layer.config.dir?.public || 'public'))
.filter(dir => existsSync(dir))
Expand Down
5 changes: 4 additions & 1 deletion packages/nuxt/src/core/templates.ts
Expand Up @@ -211,7 +211,10 @@ export const publicPathTemplate: NuxtTemplate = {
'export const publicAssetsURL = (...path) => {',
' const publicBase = appConfig.cdnURL || appConfig.baseURL',
' return path.length ? joinURL(publicBase, ...path) : publicBase',
'}'
'}',

'globalThis.__buildAssetsURL = buildAssetsURL',
'globalThis.__publicAssetsURL = publicAssetsURL'
].filter(Boolean).join('\n')
}
}
4 changes: 3 additions & 1 deletion packages/nuxt/src/pages/macros.ts
Expand Up @@ -3,6 +3,7 @@ import { createUnplugin } from 'unplugin'
import { parseQuery, parseURL, withQuery } from 'ufo'
import { findStaticImports, findExports } from 'mlly'
import MagicString from 'magic-string'
import { isAbsolute } from 'pathe'

export interface TransformMacroPluginOptions {
macros: Record<string, string>
Expand Down Expand Up @@ -48,7 +49,8 @@ export const TransformMacroPlugin = createUnplugin((options: TransformMacroPlugi
if (scriptImport) {
// https://github.com/vuejs/vue-loader/pull/1911
// https://github.com/vitejs/vite/issues/8473
const parsed = parseURL(scriptImport.specifier.replace('?macro=true', ''))
const url = isAbsolute(scriptImport.specifier) ? pathToFileURL(scriptImport.specifier).href : scriptImport.specifier
const parsed = parseURL(decodeURIComponent(url).replace('?macro=true', ''))
const specifier = withQuery(parsed.pathname, { macro: 'true', ...parseQuery(parsed.search) })
s.overwrite(0, code.length, `export { meta } from "${specifier}"`)
return result()
Expand Down
2 changes: 1 addition & 1 deletion packages/schema/package.json
Expand Up @@ -17,7 +17,7 @@
"@types/lodash.template": "^4",
"@types/semver": "^7",
"unbuild": "latest",
"vite": "^2.9.14"
"vite": "~3.0.0"
},
"dependencies": {
"c12": "^0.2.8",
Expand Down
9 changes: 2 additions & 7 deletions packages/schema/src/config/vite.ts
@@ -1,5 +1,5 @@
import { resolve } from 'pathe'
import { joinURL, withoutLeadingSlash } from 'ufo'
import { withoutLeadingSlash } from 'ufo'

export default {
/**
Expand Down Expand Up @@ -28,11 +28,6 @@ export default {
resolve: {
extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.vue'],
},
base: {
$resolve: (val, get) => val ?? get('dev')
? joinURL(get('app').baseURL, get('app').buildAssetsDir)
: '/__NUXT_BASE__/',
},
publicDir: {
$resolve: (val, get) => val ?? resolve(get('srcDir'), get('dir').public),
},
Expand Down Expand Up @@ -61,7 +56,7 @@ export default {
clearScreen: false,
build: {
assetsDir: {
$resolve: (val, get) => val ?? get('dev') ? withoutLeadingSlash(get('app').buildAssetsDir) : '.',
$resolve: (val, get) => val ?? withoutLeadingSlash(get('app').buildAssetsDir),
},
emptyOutDir: false,
},
Expand Down
6 changes: 3 additions & 3 deletions packages/vite/package.json
Expand Up @@ -21,8 +21,8 @@
"dependencies": {
"@nuxt/kit": "^3.0.0-rc.6",
"@rollup/plugin-replace": "^4.0.0",
"@vitejs/plugin-vue": "^2.3.3",
"@vitejs/plugin-vue-jsx": "^1.3.10",
"@vitejs/plugin-vue": "^3.0.0",
"@vitejs/plugin-vue-jsx": "^2.0.0",
"autoprefixer": "^10.4.7",
"chokidar": "^3.5.3",
"cssnano": "^5.1.12",
Expand All @@ -47,7 +47,7 @@
"rollup-plugin-visualizer": "^5.7.1",
"ufo": "^0.8.5",
"unplugin": "^0.7.2",
"vite": "^2.9.14",
"vite": "~3.0.0",
"vite-node": "^0.18.1",
"vite-plugin-checker": "^0.4.9"
},
Expand Down
44 changes: 37 additions & 7 deletions packages/vite/src/client.ts
@@ -1,21 +1,36 @@
import { resolve } from 'pathe'
import { join, resolve } from 'pathe'
import * as vite from 'vite'
import vuePlugin from '@vitejs/plugin-vue'
import viteJsxPlugin from '@vitejs/plugin-vue-jsx'
import type { Connect } from 'vite'
import { logger } from '@nuxt/kit'
import { joinURL } from 'ufo'
import { getPort } from 'get-port-please'
import { joinURL, withLeadingSlash, withoutLeadingSlash, withTrailingSlash } from 'ufo'
import escapeRE from 'escape-string-regexp'
import { cacheDirPlugin } from './plugins/cache-dir'
import { analyzePlugin } from './plugins/analyze'
import { wpfs } from './utils/wpfs'
import type { ViteBuildContext, ViteOptions } from './vite'
import { writeManifest } from './manifest'
import { devStyleSSRPlugin } from './plugins/dev-ssr-css'
import { RelativeAssetPlugin } from './plugins/dynamic-base'
import { viteNodePlugin } from './vite-node'

export async function buildClient (ctx: ViteBuildContext) {
const hmrPortDefault = 24678 // Vite's default HMR port
const hmrPort = await getPort({
port: hmrPortDefault,
ports: Array.from({ length: 20 }, (_, i) => hmrPortDefault + 1 + i)
})
const clientConfig: vite.InlineConfig = vite.mergeConfig(ctx.config, {
experimental: {
renderBuiltUrl: (filename, { type, hostType }) => {
if (hostType !== 'js' || type === 'asset') {
// In CSS we only use relative paths until we craft a clever runtime CSS hack
return { relative: true }
}
return { runtime: `globalThis.__publicAssetsURL(${JSON.stringify(filename)})` }
}
},
define: {
'process.server': false,
'process.client': true,
Expand All @@ -30,8 +45,10 @@ export async function buildClient (ctx: ViteBuildContext) {
build: {
rollupOptions: {
output: {
chunkFileNames: ctx.nuxt.options.dev ? undefined : '[name]-[hash].mjs',
entryFileNames: ctx.nuxt.options.dev ? 'entry.mjs' : '[name]-[hash].mjs'
// https://github.com/vitejs/vite/tree/main/packages/vite/src/node/build.ts#L464-L478
assetFileNames: ctx.nuxt.options.dev ? undefined : withoutLeadingSlash(join(ctx.nuxt.options.app.buildAssetsDir, '[name].[hash].[ext]')),
chunkFileNames: ctx.nuxt.options.dev ? undefined : withoutLeadingSlash(join(ctx.nuxt.options.app.buildAssetsDir, '[name].[hash].mjs')),
entryFileNames: ctx.nuxt.options.dev ? 'entry.mjs' : withoutLeadingSlash(join(ctx.nuxt.options.app.buildAssetsDir, '[name].[hash].mjs'))
}
},
manifest: true,
Expand All @@ -41,18 +58,30 @@ export async function buildClient (ctx: ViteBuildContext) {
cacheDirPlugin(ctx.nuxt.options.rootDir, 'client'),
vuePlugin(ctx.config.vue),
viteJsxPlugin(),
RelativeAssetPlugin(),
devStyleSSRPlugin({
rootDir: ctx.nuxt.options.rootDir,
buildAssetsURL: joinURL(ctx.nuxt.options.app.baseURL, ctx.nuxt.options.app.buildAssetsDir)
}),
viteNodePlugin(ctx)
],
appType: 'custom',
server: {
hmr: {
// https://github.com/nuxt/framework/issues/4191
protocol: 'ws',
clientPort: hmrPort,
port: hmrPort
},
middlewareMode: true
}
} as ViteOptions)

// In build mode we explicitly override any vite options that vite is relying on
// to detect whether to inject production or development code (such as HMR code)
if (!ctx.nuxt.options.dev) {
clientConfig.server.hmr = false
}

// Add analyze plugin if needed
if (ctx.nuxt.options.build.analyze) {
clientConfig.plugins.push(...analyzePlugin(ctx))
Expand All @@ -65,10 +94,11 @@ export async function buildClient (ctx: ViteBuildContext) {
const viteServer = await vite.createServer(clientConfig)
ctx.clientServer = viteServer
await ctx.nuxt.callHook('vite:serverCreated', viteServer, { isClient: true, isServer: false })

const BASE_RE = new RegExp(`^${escapeRE(withTrailingSlash(withLeadingSlash(joinURL(ctx.nuxt.options.app.baseURL, ctx.nuxt.options.app.buildAssetsDir))))}`)
const viteMiddleware: Connect.NextHandleFunction = (req, res, next) => {
// Workaround: vite devmiddleware modifies req.url
const originalURL = req.url
req.url = req.url.replace(BASE_RE, '/')
viteServer.middlewares.handle(req, res, (err) => {
req.url = originalURL
next(err)
Expand Down
8 changes: 4 additions & 4 deletions packages/vite/src/dev-bundler.ts
@@ -1,7 +1,7 @@
import { pathToFileURL } from 'node:url'
import { existsSync } from 'node:fs'
import { builtinModules } from 'node:module'
import { resolve } from 'pathe'
import { isAbsolute, resolve } from 'pathe'
import * as vite from 'vite'
import { ExternalsOptions, isExternal as _isExternal, ExternalsDefaults } from 'externality'
import { genDynamicImport, genObjectFromRawEntries } from 'knitwork'
Expand Down Expand Up @@ -77,7 +77,7 @@ async function transformRequest (opts: TransformOptions, id: string) {
if (await isExternal(opts, withoutVersionQuery)) {
const path = builtinModules.includes(withoutVersionQuery.split('node:').pop())
? withoutVersionQuery
: pathToFileURL(withoutVersionQuery).href
: isAbsolute(withoutVersionQuery) ? pathToFileURL(withoutVersionQuery).href : withoutVersionQuery
return {
code: `(global, module, _, exports, importMeta, ssrImport, ssrDynamicImport, ssrExportAll) =>
${genDynamicImport(path, { wrapper: false })}
Expand Down Expand Up @@ -140,11 +140,11 @@ export async function bundleRequest (opts: TransformOptions, entryURL: string) {
// Parents: \n${listIds(chunk.parents)}
// Dependencies: \n${listIds(chunk.deps)}
// --------------------
const ${hashId(chunk.id)} = ${chunk.code}
const ${hashId(chunk.id + '-' + chunk.code)} = ${chunk.code}
`).join('\n')

const manifestCode = `const __modules__ = ${
genObjectFromRawEntries(chunks.map(chunk => [chunk.id, hashId(chunk.id)]))
genObjectFromRawEntries(chunks.map(chunk => [chunk.id, hashId(chunk.id + '-' + chunk.code)]))
}`

// https://github.com/vitejs/vite/blob/main/packages/vite/src/node/ssr/ssrModuleLoader.ts
Expand Down
15 changes: 14 additions & 1 deletion packages/vite/src/manifest.ts
@@ -1,6 +1,7 @@
import fse from 'fs-extra'
import { resolve } from 'pathe'
import { joinURL } from 'ufo'
import { joinURL, withoutLeadingSlash, withTrailingSlash } from 'ufo'
import escapeRE from 'escape-string-regexp'
import type { ViteBuildContext } from './vite'

export async function writeManifest (ctx: ViteBuildContext, extraEntries: string[] = []) {
Expand All @@ -27,6 +28,18 @@ export async function writeManifest (ctx: ViteBuildContext, extraEntries: string
? devClientManifest
: await fse.readJSON(resolve(clientDist, 'manifest.json'))

const BASE_RE = new RegExp(`^${escapeRE(withTrailingSlash(withoutLeadingSlash(joinURL(ctx.nuxt.options.app.baseURL, ctx.nuxt.options.app.buildAssetsDir))))}`)
for (const key in clientManifest) {
if (clientManifest[key].file) {
clientManifest[key].file = clientManifest[key].file.replace(BASE_RE, '')
}
for (const item of ['css', 'assets']) {
if (clientManifest[key][item]) {
clientManifest[key][item] = clientManifest[key][item].map(i => i.replace(BASE_RE, ''))
}
}
}

await fse.mkdirp(serverDist)
await fse.writeFile(resolve(serverDist, 'client.manifest.json'), JSON.stringify(clientManifest, null, 2), 'utf8')
await fse.writeFile(resolve(serverDist, 'client.manifest.mjs'), 'export default ' + JSON.stringify(clientManifest, null, 2), 'utf8')
Expand Down
103 changes: 0 additions & 103 deletions packages/vite/src/plugins/dynamic-base.ts

This file was deleted.

0 comments on commit fa8b0f7

Please sign in to comment.