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

feat(vite)!: upgrade vite to v3 #5398

Merged
merged 58 commits into from Jul 21, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
58 commits
Select commit Hold shift + click to select a range
8069761
chore: upgrade vite to alpha
danielroe Jun 10, 2022
45700fa
test: update vitest config
danielroe Jun 10, 2022
e63cd93
fix(vite): use replace for `typeof` replacements
danielroe Jun 10, 2022
d24879b
fix: use `externalVue` for now
danielroe Jun 13, 2022
d2d8175
fix: add `#internal/nitro/utils` explicitly to externals
danielroe Jun 13, 2022
f885c2a
chore: alpha 13 and new jiti
danielroe Jun 20, 2022
596f047
fix: use custom appType
danielroe Jun 20, 2022
f4d2cb3
fix: do not alias any vue deps - and don't convert to file urls
danielroe Jun 20, 2022
5149f4b
fix: only create ws server for client build
danielroe Jun 20, 2022
e15f8ce
ci: force cache refresh
danielroe Jun 20, 2022
aaf3c8d
ci: remove cache
danielroe Jun 20, 2022
5bc2768
chore: force jiti 1.14.0
danielroe Jun 20, 2022
d923b26
chore: revert port change
danielroe Jun 20, 2022
ce0a5d2
fix: use legacy commonjs transform plugin
danielroe Jun 20, 2022
76c4df1
fix: don't need cjs transform in dev either
danielroe Jun 20, 2022
facab42
fix: use `buildAssets` dir and relative base for client
danielroe Jun 20, 2022
8d690e1
feat: use new advanced build urls to replace custom plugin
danielroe Jun 20, 2022
ddf51f6
chore: upgrade vite to latest alpha
danielroe Jun 20, 2022
7af2fff
fix: remove unused import
danielroe Jun 20, 2022
19331ea
chore: bump vite to beta
danielroe Jun 21, 2022
b90a426
chore: revert jiti resolution
danielroe Jun 22, 2022
8e8f2c2
chore: use caret version of vite packages
danielroe Jun 22, 2022
41b378e
chore: bump to beta 1
danielroe Jun 22, 2022
c29dab6
refactor: use new `renderBuiltUrl` API
danielroe Jun 28, 2022
7070281
fix: only enable `buildRollupPluginCommonjs` for vite server
danielroe Jun 30, 2022
b546037
chore: upgrade to beta 6
danielroe Jul 4, 2022
b06694c
chore: bump to beta 7
danielroe Jul 6, 2022
6c6e14f
chore: upgrade to beta 8 (reverting to use commonjs plugin by default)
danielroe Jul 8, 2022
d052426
feat: use `optimizeDeps` at build-time
danielroe Jul 8, 2022
8c83444
chore: update lockfile
danielroe Jul 8, 2022
dffbddc
fix: disable `optimizeDeps` at build-time (testing windows ci)
danielroe Jul 8, 2022
c94533f
fix: try normalizing specifier
danielroe Jul 8, 2022
c685283
fix: hotfix hashing chunk code rather than id
danielroe Jul 8, 2022
6c56217
fix: include id in hash
danielroe Jul 8, 2022
de7e8fe
fix: exclude relative paths from new approach
danielroe Jul 8, 2022
c16a56a
fix: hash manifest as well
danielroe Jul 8, 2022
b91ff93
chore: upgrade to beta 9
danielroe Jul 8, 2022
b37cfb4
chore: bump vite to beta 10
danielroe Jul 12, 2022
8c36c27
fix: revert unneeded changes
danielroe Jul 12, 2022
7a5fa22
docs: add link to source
danielroe Jul 12, 2022
bdca0b7
fix: don't alias vue deps in dev mode
danielroe Jul 12, 2022
bdde1fd
chore: use released vite 3 packages
danielroe Jul 13, 2022
bf4a51e
Merge remote-tracking branch 'origin/main' into chore/vite-3
danielroe Jul 13, 2022
0da80d5
Merge remote-tracking branch 'origin/main' into chore/vite-3
danielroe Jul 13, 2022
f4bdd62
Update packages/vite/src/client.ts
danielroe Jul 13, 2022
c740bd2
Update packages/vite/src/server.ts
danielroe Jul 13, 2022
f46330b
Update packages/vite/src/server.ts
danielroe Jul 13, 2022
6d4aaeb
Merge branch 'main' into chore/vite-3
pi0 Jul 14, 2022
f4ebe8b
Merge remote-tracking branch 'origin/main' into chore/vite-3
danielroe Jul 18, 2022
c4f451b
fix(components): transform `<script setup>` blocks with new vite vue …
danielroe Jul 18, 2022
582d3a5
Merge remote-tracking branch 'origin/main' into chore/vite-3
danielroe Jul 18, 2022
616ab1e
fix: type error
danielroe Jul 18, 2022
ab4dd6e
Merge remote-tracking branch 'origin/main' into chore/vite-3
danielroe Jul 21, 2022
376b87e
fix: remove debugging code
danielroe Jul 21, 2022
b23d738
fix: revert change from define -> replace
danielroe Jul 21, 2022
28ccf68
Merge branch 'main' into chore/vite-3
pi0 Jul 21, 2022
d0a3bab
refactor: use simple if
pi0 Jul 21, 2022
b832953
refactor webpack plugin
pi0 Jul 21, 2022
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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",
pi0 marked this conversation as resolved.
Show resolved Hide resolved
"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
danielroe marked this conversation as resolved.
Show resolved Hide resolved
// 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.