-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
156 lines (133 loc) · 4.7 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
import { resolve, relative } from 'path'
import fs from 'fs'
import lodash from 'lodash'
import nunjucks from 'nunjucks'
import {
getPackageInfo,
merge,
pluginBundle,
pluginMiddleware,
pluginReload,
pluginTransform,
processData
} from 'vituum/utils/common.js'
import { renameBuildEnd, renameBuildStart } from 'vituum/utils/build.js'
const { name } = getPackageInfo(import.meta.url)
/**
* @type {import('@vituum/vite-plugin-nunjucks/types').PluginUserConfig}
*/
const defaultOptions = {
reload: true,
root: null,
filters: {},
extensions: {},
globals: {
format: 'njk'
},
data: ['src/data/**/*.json'],
formats: ['njk', 'json.njk', 'json'],
ignoredPaths: [],
options: {}
}
const renderTemplate = async ({ filename, server, resolvedConfig }, content, options) => {
const initialFilename = filename.replace('.html', '')
const output = {}
const context = options.data
? processData({
paths: options.data,
root: resolvedConfig.root
}, options.globals)
: options.globals
if (initialFilename.endsWith('.json')) {
lodash.merge(context, JSON.parse(content))
if (!options.formats.includes(context.format)) {
return new Promise((resolve) => {
output.content = content
resolve(output)
})
}
output.template = true
if (typeof context.template === 'undefined') {
const error = `${name}: template must be defined for file ${initialFilename}`
return new Promise((resolve) => {
output.error = error
resolve(output)
})
}
context.template = relative(resolvedConfig.root, context.template).startsWith(relative(resolvedConfig.root, options.root)) ? resolve(resolvedConfig.root, context.template) : resolve(options.root, context.template)
} else if (fs.existsSync(`${initialFilename}.json`)) {
lodash.merge(context, JSON.parse(fs.readFileSync(`${initialFilename}.json`).toString()))
}
const nunjucksEnvironment = nunjucks.configure(options.root, Object.assign({
noCache: true
}, options.options))
Object.keys(options.filters).forEach(name => {
if (typeof options.filters[name] !== 'function') {
throw new TypeError(`${name} needs to be a function!`)
}
nunjucksEnvironment.addFilter(name, options.filters[name])
})
Object.keys(options.extensions).forEach(name => {
if (typeof options.extensions[name] !== 'function') {
throw new TypeError(`${name} needs to be an function!`)
}
nunjucksEnvironment.addExtension(name, new options.extensions[name]())
})
return new Promise((resolve) => {
const callback = (error, content) => {
if (error) {
output.error = error
resolve(output)
} else {
output.content = content
resolve(output)
}
}
if (output.template) {
nunjucksEnvironment.render(context.template, context, callback)
} else {
nunjucksEnvironment.renderString(content, context, callback)
}
})
}
/**
* @param {import('@vituum/vite-plugin-nunjucks/types').PluginUserConfig} options
* @returns [import('vite').Plugin]
*/
const plugin = (options = {}) => {
let resolvedConfig
let userEnv
options = merge(defaultOptions, options)
return [{
name,
config (userConfig, env) {
userEnv = env
},
configResolved (config) {
resolvedConfig = config
if (!options.root) {
options.root = config.root
}
},
buildStart: async () => {
if (userEnv.command !== 'build' || !resolvedConfig.build.rollupOptions.input) {
return
}
await renameBuildStart(resolvedConfig.build.rollupOptions.input, options.formats)
},
buildEnd: async () => {
if (userEnv.command !== 'build' || !resolvedConfig.build.rollupOptions.input) {
return
}
await renameBuildEnd(resolvedConfig.build.rollupOptions.input, options.formats)
},
transformIndexHtml: {
order: 'pre',
async handler (content, { path, filename, server }) {
return pluginTransform(content, { path, filename, server }, { name, options, resolvedConfig, renderTemplate })
}
},
handleHotUpdate: ({ file, server }) => pluginReload({ file, server }, options)
}, pluginBundle(options.formats), pluginMiddleware(name, options.formats)]
}
export default plugin