-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
76 lines (63 loc) · 1.75 KB
/
index.js
File metadata and controls
76 lines (63 loc) · 1.75 KB
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
import { dirname, join, resolve } from 'node:path'
import fs from 'node:fs'
import { globSync } from 'tinyglobby'
/**
* @param {import('@vituum/vite-plugin-concat/types').PluginUserOptions} userOptions
* @returns {import('vite').Plugin}
*/
const plugin = (userOptions) => {
const options = {
input: [],
files: [],
...userOptions,
}
let resolvedConfig
const importJs = (path) => {
let content = fs.readFileSync(path, {
encoding: 'utf8',
})
content = content.replace(/import\s["'](.*\.js)["']/gi, (match, fileName) => {
const importPath = join(dirname(path), fileName)
return importJs(importPath)
})
return content
}
return {
name: '@vituum/vite-plugin-concat',
enforce: 'pre',
configResolved(config) {
resolvedConfig = config
},
transform(code, path) {
if (options.input.find(input => path.split('?')[0].endsWith(input))) {
code = importJs(path.split('?')[0])
const filesInput = Object.keys(options.files).find(input => path.split('?')[0].endsWith(input))
if (filesInput) {
globSync(options.files[filesInput].map(entry => resolve(resolvedConfig.root, entry))).forEach((entry) => {
const file = fs.readFileSync(entry).toString()
code = code + '\n' + file
})
}
return {
code,
map: null,
}
}
return {
code,
map: null,
}
},
transformIndexHtml: {
async handler(content, { server }) {
if (server) {
options.input.forEach((input) => {
content = content.replace(input, `${input}?v=${Date.now().toString(36)}`)
})
return content
}
},
},
}
}
export default plugin