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: custom template compiler for sfc #488

Closed
wants to merge 7 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion playground/App.vue
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
<Suspense>
<TestWasm />
</Suspense>
<TestCustomCompiler/>
</template>

<script>
Expand Down Expand Up @@ -54,6 +55,7 @@ import TestRewriteOptimized from './resolve/rewrite-optimized/TestRewriteOptimiz
import TestDynamicImport from './dynamic-import/TestDynamicImport.vue'
import TestWebWorker from './worker/TestWorker.vue'
import TestWasm from './wasm/TestWasm.vue'
import TestCustomCompiler from './test-custom-compiler/test-custom-compiler.vue'

export default {
components: {
Expand All @@ -80,7 +82,8 @@ export default {
TestNormalizePublicPath,
TestDynamicImport,
TestWebWorker,
TestWasm
TestWasm,
TestCustomCompiler
}
}
</script>
7 changes: 7 additions & 0 deletions playground/test-custom-compiler/test-custom-compiler.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<template compiler="custom">
<div></div>
</template>

<script>
export default {}
</script>
13 changes: 13 additions & 0 deletions playground/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,16 @@ import type { UserConfig } from 'vite'
import { jsPlugin } from './plugins/jsPlugin'
import { i18nTransform } from './custom-blocks/i18nTransform'

const customCompiler = {
compile: () => {
return {
code: `import {h} from '/@modules/vue'\n export function render () { return [[h('h2', 'Custom Compiler'), h('div', {class: 'custom-compiler'}, 'custom compiler works!')]]}`,
ast: null
}
},
parse: () => null
}

const config: UserConfig = {
alias: {
alias: '/alias/aliased',
Expand All @@ -11,6 +21,9 @@ const config: UserConfig = {
minify: false,
serviceWorker: !!process.env.USE_SW,
plugins: [jsPlugin],
vueTemplateCompilers: {
custom: customCompiler
},
vueCustomBlockTransforms: { i18n: i18nTransform },
optimizeDeps: {
exclude: ['bootstrap', 'rewrite-unoptimized-test-package'],
Expand Down
2 changes: 2 additions & 0 deletions src/node/build/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,9 @@ export async function createBaseRollupPlugins(
...cssPreprocessOptions
},
preprocessCustomRequire: (id: string) => require(resolveFrom(root, id)),
compiler: options.vueCompiler,
compilerOptions: options.vueCompilerOptions,
templateCompilers: options.vueTemplateCompilers,
cssModulesOptions: {
generateScopedName: (local: string, filename: string) =>
`${local}_${hash_sum(filename)}`,
Expand Down
20 changes: 19 additions & 1 deletion src/node/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,11 @@ import chalk from 'chalk'
import dotenv, { DotenvParseOutput } from 'dotenv'
import dotenvExpand from 'dotenv-expand'
import { Options as RollupPluginVueOptions } from 'rollup-plugin-vue'
import { CompilerOptions, SFCStyleCompileOptions } from '@vue/compiler-sfc'
import {
CompilerOptions,
SFCStyleCompileOptions,
TemplateCompiler
} from '@vue/compiler-sfc'
import Rollup, {
InputOptions as RollupInputOptions,
OutputOptions as RollupOutputOptions,
Expand All @@ -18,6 +22,7 @@ import { DepOptimizationOptions } from './optimizer'
import { IKoaProxiesOptions } from 'koa-proxies'
import { ServerOptions } from 'https'
import { lookupFile } from './utils'
import { TemplateCompilers } from './server/serverPluginVue'

export { Resolver, Transform }

Expand Down Expand Up @@ -80,6 +85,14 @@ export interface SharedConfig {
* https://github.com/vuejs/vue-next/blob/master/packages/compiler-core/src/options.ts
*/
vueCompilerOptions?: CompilerOptions
/**
* Customer template compiler for global sfc template block.
*/
vueCompiler?: TemplateCompiler
/**
* Customer template compiler for special sfc template block.
*/
vueTemplateCompilers?: Record<string, TemplateCompilers>
/**
* Transform functions for Vue custom blocks.
*
Expand Down Expand Up @@ -275,6 +288,7 @@ export interface Plugin
| 'transforms'
| 'resolvers'
| 'configureServer'
| 'vueTemplateCompilers'
| 'vueCompilerOptions'
| 'vueCustomBlockTransforms'
| 'rollupInputOptions'
Expand Down Expand Up @@ -430,6 +444,10 @@ function resolvePlugin(config: UserConfig, plugin: Plugin): UserConfig {
config.configureServer || [],
plugin.configureServer || []
),
vueTemplateCompilers: {
...config.vueTemplateCompilers,
...plugin.vueTemplateCompilers
},
vueCompilerOptions: {
...config.vueCompilerOptions,
...plugin.vueCompilerOptions
Expand Down
40 changes: 35 additions & 5 deletions src/node/server/serverPluginVue.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
import qs from 'querystring'
import chalk from 'chalk'
import path from 'path'
import { Context, ServerPlugin } from '.'
import { Context, ServerPlugin, ServerPluginContext } from '.'
import {
SFCBlock,
SFCDescriptor,
SFCTemplateBlock,
SFCStyleBlock,
SFCStyleCompileResults,
CompilerOptions,
SFCStyleCompileOptions
SFCStyleCompileOptions,
TemplateCompiler
} from '@vue/compiler-sfc'
import { resolveCompiler, resolveVue } from '../utils/resolveVue'
import hash_sum from 'hash-sum'
Expand Down Expand Up @@ -124,7 +125,7 @@ export const vuePlugin: ServerPlugin = ({
filePath,
publicPath,
descriptor.styles.some((s) => s.scoped),
config.vueCompilerOptions
config
)
ctx.body = code
ctx.map = map
Expand Down Expand Up @@ -498,20 +499,48 @@ async function compileSFCMain(
return result
}

export type TemplateCompilers =
| TemplateCompiler
| [TemplateCompiler, CompilerOptions]

function compileSFCTemplate(
root: string,
template: SFCTemplateBlock,
filePath: string,
publicPath: string,
scoped: boolean,
userOptions: CompilerOptions | undefined
{
vueCompilerOptions = {},
vueTemplateCompilers,
vueCompiler
}: ServerPluginContext['config']
): ResultWithMap {
let cached = vueCache.get(filePath)
if (cached && cached.template) {
debug(`${publicPath} template cache hit`)
return cached.template
}

const compilerKey = template.attrs.compiler
if (compilerKey) {
if (typeof compilerKey === 'string') {
if (vueTemplateCompilers && vueTemplateCompilers[compilerKey]) {
const compilers = vueTemplateCompilers[compilerKey]
if (Array.isArray(compilers)) {
;[vueCompiler, vueCompilerOptions] = compilers
} else {
vueCompiler = compilers
}
} else {
console.error(
`The "${compilerKey}" compiler not found.Please add "vueTemplateCompilers" options.`
)
}
} else {
console.error(`Please ensure custom template compiler in ${filePath}`)
}
}

const start = Date.now()
const { compileTemplate, generateCodeFrame } = resolveCompiler(root)
const { code, map, errors } = compileTemplate({
Expand All @@ -521,8 +550,9 @@ function compileSFCTemplate(
transformAssetUrls: {
base: path.posix.dirname(publicPath)
},
compiler: vueCompiler,
compilerOptions: {
...userOptions,
...vueCompilerOptions,
scopeId: scoped ? `data-v-${hash_sum(publicPath)}` : null,
runtimeModuleName: resolveVue(root).isLocal
? // in local mode, vue would have been optimized so must be referenced
Expand Down
7 changes: 7 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -630,6 +630,13 @@ describe('vite', () => {
await button.click()
await expectByPolling(() => getText('.wasm-response'), '42')
})

test('custom compiler', async () => {
await expectByPolling(
() => getText('.custom-compiler'),
'custom compiler works!'
)
})
}

// test build first since we are going to edit the fixtures when testing dev
Expand Down