Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support pre-bundle #187

Closed
wants to merge 15 commits into from
Closed
Show file tree
Hide file tree
Changes from 3 commits
Commits
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
7 changes: 7 additions & 0 deletions packages/plugin-vue/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,13 @@ export interface Options {
* Use custom compiler-sfc instance. Can be used to force a specific version.
*/
compiler?: typeof _compiler

/**
* Prebundle SFC libs
sxzz marked this conversation as resolved.
Show resolved Hide resolved
*
* @default true
*/
prebundleSfc?: boolean
sxzz marked this conversation as resolved.
Show resolved Hide resolved
}
```

Expand Down
15 changes: 14 additions & 1 deletion packages/plugin-vue/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import { handleHotUpdate, handleTypeDepChange } from './handleHotUpdate'
import { transformTemplateAsModule } from './template'
import { transformStyle } from './style'
import { EXPORT_HELPER_ID, helperCode } from './helper'
import { createOptimizeDeps, patchOptimizeDeps } from './prebundle'

export { parseVueRequest } from './utils/query'
export type { VueQuery } from './utils/query'
Expand Down Expand Up @@ -78,6 +79,13 @@ export interface Options {
* Use custom compiler-sfc instance. Can be used to force a specific version.
*/
compiler?: typeof _compiler

/**
* Prebundle SFC libs
*
* @default true
*/
prebundleSfc?: boolean
sxzz marked this conversation as resolved.
Show resolved Hide resolved
}

export interface ResolvedOptions extends Options {
Expand Down Expand Up @@ -140,7 +148,9 @@ export default function vuePlugin(rawOptions: Options = {}): Plugin {
}
},

config(config) {
config(config, env) {
options.prebundleSfc ??= env.command === 'serve'

return {
resolve: {
dedupe: config.build?.ssr ? [] : ['vue'],
Expand All @@ -154,6 +164,7 @@ export default function vuePlugin(rawOptions: Options = {}): Plugin {
? ['vue', '@vue/server-renderer']
: [],
},
optimizeDeps: createOptimizeDeps(config, options),
}
},

Expand All @@ -167,6 +178,8 @@ export default function vuePlugin(rawOptions: Options = {}): Plugin {
devToolsEnabled:
!!config.define!.__VUE_PROD_DEVTOOLS__ || !config.isProduction,
}

patchOptimizeDeps(config, options)
},

configureServer(server) {
Expand Down
153 changes: 153 additions & 0 deletions packages/plugin-vue/src/prebundle.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
import { readFileSync } from 'node:fs'
import { dirname } from 'node:path'
import type { DepOptimizationOptions, ResolvedConfig, UserConfig } from 'vite'
import { createFilter, normalizePath } from 'vite'
import { transformMain } from './main'
import { EXPORT_HELPER_ID, helperCode } from './helper'
import type { ResolvedOptions } from './index'

type ESBuildPlugin = NonNullable<
NonNullable<DepOptimizationOptions['esbuildOptions']>['plugins']
>[0]
sxzz marked this conversation as resolved.
Show resolved Hide resolved

const FACADE_PLUGIN: ESBuildPlugin = {
name: 'vite-plugin-vue:facade-prebundle',
sxzz marked this conversation as resolved.
Show resolved Hide resolved
setup: () => {},
}

const PLUGIN_NAME = 'vite-plugin-vue:prebundle'
sxzz marked this conversation as resolved.
Show resolved Hide resolved

export function createOptimizeDeps(
config: UserConfig,
options: ResolvedOptions,
): DepOptimizationOptions | undefined {
if (!options.prebundleSfc) {
return config.optimizeDeps
}

const nextOptimizeDeps = (config.optimizeDeps ||= {})
const exts = (nextOptimizeDeps.extensions ||= [])
exts.push('.vue')
sxzz marked this conversation as resolved.
Show resolved Hide resolved

const esbuildOpts = (nextOptimizeDeps.esbuildOptions ||= {})
const plugins = (esbuildOpts.plugins ||= [])
plugins.push(FACADE_PLUGIN)

return nextOptimizeDeps
}

export function patchOptimizeDeps(
sxzz marked this conversation as resolved.
Show resolved Hide resolved
config: ResolvedConfig,
options: ResolvedOptions,
): void {
const plugins = config.optimizeDeps.esbuildOptions?.plugins
if (!Array.isArray(plugins)) return

const index = plugins.indexOf(FACADE_PLUGIN)
if (index == null || index < 0) return

plugins.splice(index, 1, createPrebundlePlugin(options))
}

function createPrebundlePlugin(options: ResolvedOptions): ESBuildPlugin {
const helperFilter = createHelperFilter()
const transformFilter = createTransformLoadFilter(options)
const customElementFilter = createCustomElementFilter(options)

return {
name: PLUGIN_NAME,
setup(build) {
if (build.initialOptions.plugins?.some((v) => v.name === 'vite:dep-scan'))
return

build.onResolve({ filter: helperFilter }, async ({ path: filename }) => {
if (normalizePath(filename) === EXPORT_HELPER_ID) {
return { path: filename, namespace: PLUGIN_NAME }
}
})

build.onLoad({ filter: helperFilter }, async ({ path: filename }) => {
return {
contents: helperCode,
resolveDir: dirname(filename),
loader: 'js',
}
})

build.onLoad(
{ filter: transformFilter.regexp },
async ({ path: filename }) => {
if (!transformFilter.guard(filename)) return

const { errors, warnings, pluginContext } = createFakeContext()
const resolveDir = dirname(filename)
const code = readFileSync(filename, 'utf8')
sxzz marked this conversation as resolved.
Show resolved Hide resolved
const asCustomElement = customElementFilter(filename)
const transformed = await transformMain(
code,
filename,
options,
pluginContext,
false,
asCustomElement,
)

return {
contents: transformed?.code,
errors,
warnings,
resolveDir,
loader: 'js',
}
},
)
},
}
}

function createHelperFilter() {
return new RegExp(`${EXPORT_HELPER_ID}$`)
sxzz marked this conversation as resolved.
Show resolved Hide resolved
}

function createTransformLoadFilter(options: ResolvedOptions) {
const { include, exclude } = options

if (include instanceof RegExp) {
return {
regexp: include,
guard: createFilter(undefined, exclude),
}
}

return {
regexp: /.*/,
guard: createFilter(include, exclude),
}
}

function createCustomElementFilter(options: ResolvedOptions) {
const { customElement } = options

return typeof customElement === 'boolean'
? () => !!customElement
aa900031 marked this conversation as resolved.
Show resolved Hide resolved
: createFilter(customElement)
}

function createFakeContext() {
const errors: { text: string }[] = []
const warnings: { text: string }[] = []
const pluginContext = {
error(message: any) {
errors.push({ text: String(message) })
},
warn(message: any) {
warnings.push({ text: String(message) })
},
} as any

return {
errors,
warnings,
pluginContext,
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { describe, expect, it } from 'vitest'
import { isServe, page, readVitePrebundleFile } from '~utils'

describe('prebundle Vue SFC library', () => {
it('should page work', async () => {
expect(await page.textContent('span:nth-child(1)')).toMatch('hello A')
expect(await page.textContent('span:nth-child(2)')).toMatch('hello B')
expect(await page.textContent('span:nth-child(3)')).toMatch('hello C')
expect(await page.textContent('span:nth-child(4)')).toMatch('hello D')
})

it.runIf(isServe)('should prebundle @vitejs/test-lib-component', () => {
const metadata = JSON.parse(readVitePrebundleFile('_metadata.json'))
const target = metadata.optimized['@vitejs/test-lib-component']
expect(target).toBeDefined()

const bundled = readVitePrebundleFile(target.file)
expect(bundled).toContain(
'var CompA_default = plugin_vue_export_helper_default(_sfc_main',
)
expect(bundled).toContain(
'var CompB_default = plugin_vue_export_helper_default(_sfc_main',
)
expect(bundled).toContain(
'var CompC_default = plugin_vue_export_helper_default(_sfc_main',
)
expect(bundled).toContain(
'var CompD_default = plugin_vue_export_helper_default(_sfc_main',
)
})
})
6 changes: 6 additions & 0 deletions playground/prebundle-vue-sfc-lib/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<html>
<body>
<div id="app"></div>
<script type="module" src="src/main.ts"></script>
</body>
</html>
14 changes: 14 additions & 0 deletions playground/prebundle-vue-sfc-lib/lib-component/CompA.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<script>
export default {
name: 'CompA',
setup() {
return {
message: 'hello A',
}
},
}
</script>

<template>
<span>{{ message }}</span>
</template>
7 changes: 7 additions & 0 deletions playground/prebundle-vue-sfc-lib/lib-component/CompB.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<script setup>
const message = 'hello B'
</script>

<template>
<span>{{ message }}</span>
</template>
16 changes: 16 additions & 0 deletions playground/prebundle-vue-sfc-lib/lib-component/CompC.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<script lang="ts">
import { defineComponent } from 'vue'

export default defineComponent({
name: 'CompC',
setup() {
return {
message: 'hello C',
}
},
})
</script>

<template>
<span>{{ message }}</span>
</template>
7 changes: 7 additions & 0 deletions playground/prebundle-vue-sfc-lib/lib-component/CompD.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<script setup lang="ts">
const message: string = 'hello D'
</script>

<template>
<span>{{ message }}</span>
</template>
4 changes: 4 additions & 0 deletions playground/prebundle-vue-sfc-lib/lib-component/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export { default as CompA } from './CompA.vue'
export { default as CompB } from './CompB.vue'
export { default as CompC } from './CompC.vue'
export { default as CompD } from './CompD.vue'
7 changes: 7 additions & 0 deletions playground/prebundle-vue-sfc-lib/lib-component/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"name": "@vitejs/test-lib-component",
"private": true,
"version": "0.0.0",
"type": "module",
"main": "index.js"
}
18 changes: 18 additions & 0 deletions playground/prebundle-vue-sfc-lib/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"name": "@vitejs/test-prebundle-vue-sfc-lib",
"private": true,
"version": "0.0.0",
"scripts": {
"dev": "vite",
"build": "vite build",
"debug": "node --inspect-brk vite",
"preview": "vite preview"
},
"dependencies": {
"@vitejs/test-lib-component": "file:./lib-component",
"vue": "^3.3.0-beta.5"
},
"devDependencies": {
"@vitejs/plugin-vue": "workspace:*"
}
}
10 changes: 10 additions & 0 deletions playground/prebundle-vue-sfc-lib/src/App.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<script setup>
import { CompA, CompB, CompC, CompD } from '@vitejs/test-lib-component'
</script>

<template>
<CompA />
<CompB />
<CompC />
<CompD />
</template>
5 changes: 5 additions & 0 deletions playground/prebundle-vue-sfc-lib/src/main.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { createApp } from 'vue'
import App from './App.vue'

const app = createApp(App)
app.mount('#app')
7 changes: 7 additions & 0 deletions playground/prebundle-vue-sfc-lib/vite.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

export default defineConfig({
root: __dirname,
plugins: [vue()],
})
19 changes: 19 additions & 0 deletions playground/test-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -317,3 +317,22 @@ export async function killProcess(
serverProcess.kill('SIGTERM', { forceKillAfterTimeout: 2000 })
}
}

export function readVitePrebundleFile(file: string): string {
const paths = [
`node_modules/.vite/${file}`,
`node_modules/.vite/deps/${file}`, // vite 2.9
]

for (const p of paths) {
try {
const fullpath = path.resolve(testDir, p)
const content = fs.readFileSync(fullpath, 'utf8')
return content
} catch {
// ignore
}
}

throw new Error(`Unable to find vite prebundle file (${file})`)
}