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 11 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 @@ -73,6 +73,13 @@ export interface Options {
* Use custom compiler-sfc instance. Can be used to force a specific version.
*/
compiler?: typeof _compiler

/**
* Pre-bundle SFC files
*
* @default true
*/
prebundle?: boolean
}
```

Expand Down
2 changes: 2 additions & 0 deletions packages/plugin-vue/src/helper.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
export const EXPORT_HELPER_ID = '\0plugin-vue:export-helper'

export const EXPORT_HELPER_ID_RE = /plugin-vue:export-helper$/

export const helperCode = `
export default (sfc, props) => {
const target = sfc.__vccOpts || sfc;
Expand Down
17 changes: 15 additions & 2 deletions 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 } from './prebundle'

export { parseVueRequest } from './utils/query'
export type { VueQuery } from './utils/query'
Expand Down Expand Up @@ -80,6 +81,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
*/
prebundle?: boolean
sxzz marked this conversation as resolved.
Show resolved Hide resolved
}

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

let options: ResolvedOptions = {
isProduction: process.env.NODE_ENV === 'production',
compiler: null as any, // to be set in buildStart
compiler: null as any, // to be set in configResolved or buildStart
...rawOptions,
include,
exclude,
Expand All @@ -142,7 +150,9 @@ export default function vuePlugin(rawOptions: Options = {}): Plugin {
}
},

config(config) {
config(config, env) {
options.prebundle ??= env.command === 'serve'
sxzz marked this conversation as resolved.
Show resolved Hide resolved

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

Expand All @@ -169,13 +180,15 @@ export default function vuePlugin(rawOptions: Options = {}): Plugin {
devToolsEnabled:
!!config.define!.__VUE_PROD_DEVTOOLS__ || !config.isProduction,
}
options.compiler = options.compiler || resolveCompiler(options.root)
},

configureServer(server) {
options.devServer = server
},

buildStart() {
// compatible with Rollup
const compiler = (options.compiler =
options.compiler || resolveCompiler(options.root))
if (compiler.invalidateTypeCache) {
Expand Down
135 changes: 135 additions & 0 deletions packages/plugin-vue/src/prebundle.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
import { readFile } from 'node:fs/promises'
import { dirname } from 'node:path'
import type { DepOptimizationOptions, UserConfig } from 'vite'
import { createFilter, normalizePath } from 'vite'
import { transformMain } from './main'
import { EXPORT_HELPER_ID, EXPORT_HELPER_ID_RE, helperCode } from './helper'
import type { ResolvedOptions } from './index'

type ESBuildPlugin = NonNullable<
NonNullable<DepOptimizationOptions['esbuildOptions']>['plugins']
>[number]

const PLUGIN_NAME = 'vite-vue:prebundle'

export function createOptimizeDeps(
config: UserConfig,
options: () => ResolvedOptions,
): DepOptimizationOptions | undefined {
const opts = options()
if (!opts.prebundle) {
return config.optimizeDeps
}

const nextOptimizeDeps = (config.optimizeDeps ||= {})
const exts = (nextOptimizeDeps.extensions ||= [])
if (!exts.includes('.vue')) {
exts.push('.vue')
}

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

return nextOptimizeDeps
}

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

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 = await readFile(filename, 'utf8')
const asCustomElement = customElementFilter(filename)
const transformed = await transformMain(
code,
filename,
options(),
pluginContext,
false,
asCustomElement,
)

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

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
: 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})`)
}