-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
78 lines (64 loc) · 2.41 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import posthtmlExtend from 'posthtml-extend'
import posthtmlInclude from 'posthtml-include'
import posthtml from 'posthtml'
import { dirname } from 'path'
import { getPackageInfo, merge, pluginError, normalizePath } from 'vituum/utils/common.js'
const { name } = getPackageInfo(import.meta.url)
/**
* @type {import('@vituum/vite-plugin-posthtml/types').PluginUserConfig} pluginOptions
*/
const defaultOptions = {
root: null,
extend: {},
include: {},
plugins: [],
options: {}
}
/**
* @param {import('@vituum/vite-plugin-posthtml/types').PluginUserConfig} pluginOptions
* @returns {import('vite').Plugin}
*/
const plugin = (pluginOptions = {}) => {
pluginOptions = merge(defaultOptions, pluginOptions)
if (pluginOptions.root) {
pluginOptions.root = normalizePath(pluginOptions.root)
}
return {
name,
enforce: 'pre',
transformIndexHtml: {
order: 'pre',
handler: async (html, { filename, server }) => {
if (filename.replace('.html', '').endsWith('.json') && html.startsWith('{')) {
return html
}
const plugins = []
if (pluginOptions.extend) {
plugins.push(posthtmlExtend({ root: pluginOptions.root ? pluginOptions.root : dirname(filename), ...pluginOptions.extend }))
}
if (pluginOptions.include) {
plugins.push(posthtmlInclude({ root: pluginOptions.root ? pluginOptions.root : dirname(filename), ...pluginOptions.include }))
}
const render = await new Promise((resolve) => {
const output = {}
posthtml(plugins.concat(...pluginOptions.plugins)).process(html, pluginOptions.options).catch(error => {
output.error = error
resolve(output)
}).then(result => {
// @ts-ignore
output.content = result?.html
resolve(output)
})
})
const renderError = pluginError(render.error, server, name)
if (renderError && server) {
return
} else if (renderError) {
return renderError
}
return render.content
}
}
}
}
export default plugin