-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathvite-minify-plugin.ts
More file actions
32 lines (29 loc) · 997 Bytes
/
vite-minify-plugin.ts
File metadata and controls
32 lines (29 loc) · 997 Bytes
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
import { transform as esbuildTransform } from 'esbuild'
import type { Plugin } from 'vite'
export default function minifyScriptPlugin(): Plugin {
return {
name: 'vite-plugin-minify-script',
enforce: 'pre',
transform: {
filter: { id: /\?script-string$/ },
async handler(code) {
const result = await esbuildTransform(code, {
loader: 'ts',
minify: true,
target: 'esnext',
})
// Source files may use `export default …`. esbuild preserves that,
// but we need a bare expression so it can be embedded in inline
// scripts (e.g. as an IIFE: `(function(…){…})(args)`).
// Strip `export default` and any trailing semicolon/whitespace.
const normalizedCode = result.code
.replace(/^export default /, '')
.replace(/;?\s*$/, '')
return {
code: `export default ${JSON.stringify(normalizedCode)};`,
map: null,
}
},
},
}
}