Skip to content

Commit

Permalink
chore: example of helper from virtual module
Browse files Browse the repository at this point in the history
  • Loading branch information
patak-dev committed Jun 27, 2022
1 parent b02ad7a commit 7b7f0b7
Showing 1 changed file with 76 additions and 2 deletions.
78 changes: 76 additions & 2 deletions playground/ssr-vue/vite.config.js
@@ -1,13 +1,17 @@
import path from 'path'
import { defineConfig } from 'vite'
import vuePlugin from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'

const virtualFile = '@virtual-file'
const virtualId = '\0' + virtualFile
const nestedVirtualFile = '@nested-virtual-file'
const nestedVirtualId = '\0' + nestedVirtualFile

const base = '/test/'

export default defineConfig({
base: '/test/',
base,
plugins: [
vuePlugin(),
vueJsx(),
Expand Down Expand Up @@ -40,8 +44,78 @@ export default defineConfig({
return `export const msg = "[success] from conventional virtual file"`
}
}
}
},
{
name: 'virtual-module',
resolveId(id) {
if (id === virtualFile) {
return virtualId
} else if (id === nestedVirtualFile) {
return nestedVirtualId
}
},
load(id) {
if (id === virtualId) {
return `export { msg } from "@nested-virtual-file";`
} else if (id === nestedVirtualId) {
return `export const msg = "[success] from conventional virtual file"`
}
}
},
// Example of a plugin that injects a helper from a virtual module that can
// be used in renderBuiltUrl
(function () {
const queryRE = /\?.*$/s
const hashRE = /#.*$/s
const cleanUrl = (url) => url.replace(hashRE, '').replace(queryRE, '')
let config

const virtualId = '\0virtual:ssr-vue-built-url'
return {
name: 'built-url',
enforce: 'post',
configResolved(_config) {
config = _config
},
resolveId(id) {
if (id === virtualId) {
return id
}
},
load(id) {
if (id === virtualId) {
return {
code: `export const __ssr_vue_processAssetPath = (url) => '${base}' + url`,
moduleSideEffects: 'no-treeshake'
}
}
},
transform(code, id) {
if (
config.build.ssr &&
cleanUrl(id).endsWith('.js') &&
!code.includes('__ssr_vue_processAssetPath')
) {
return {
code:
`import { __ssr_vue_processAssetPath } from '${virtualId}';` +
code,
sourcemap: null // no sourcemap support to speed up CI
}
}
}
}
})()
],
experimental: {
renderBuiltUrl(filename, importer, { type, ssr }) {
if (type === 'asset' && ssr && path.extname(importer) === '.js') {
return {
runtime: `__ssr_vue_processAssetPath(${JSON.stringify(filename)})`
}
}
}
},
build: {
minify: false
},
Expand Down

0 comments on commit 7b7f0b7

Please sign in to comment.