-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathrolldown.ts
More file actions
95 lines (90 loc) · 2.71 KB
/
rolldown.ts
File metadata and controls
95 lines (90 loc) · 2.71 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import type { Plugin } from 'rolldown'
import type { CompilerOptions, TransformResult } from './types'
import path from 'node:path'
import process from 'node:process'
import { pathToFileURL } from 'node:url'
import JSON5 from 'json5'
import { normalizePath } from '../utils'
import { aliasMatches } from './esbuild'
const renamePlugin: Plugin = {
name: 'vite-mock:rename-plugin',
resolveId(id) {
if (id === 'vite-plugin-mock-dev-server') {
return {
id: 'vite-plugin-mock-dev-server/helper',
external: true,
}
}
},
}
const json5Plugin: Plugin = {
name: 'vite-mock:json5-plugin',
transform: {
filter: { id: /\.json5$/ },
handler: (code) => {
return { code: `export default ${JSON5.stringify(JSON5.parse(code))}` }
},
},
}
let _rolldown: null | {
build: typeof import('rolldown').build
aliasPlugin: typeof import('rolldown/experimental').viteAliasPlugin
} = null
async function rolldown() {
_rolldown ||= {
build: (await import('rolldown')).build,
aliasPlugin: (await import('rolldown/experimental')).viteAliasPlugin,
}
return _rolldown
}
export async function transformWithRolldown(
entryPoint: string,
{ isESM = true, define, alias, cwd = process.cwd() }: CompilerOptions,
): Promise<TransformResult> {
const filepath = path.resolve(cwd, entryPoint)
const filename = path.basename(entryPoint)
const dirname = path.dirname(filepath)
const isAlias = (p: string) => !!alias.find(({ find }) => aliasMatches(find, p))
try {
const { build, aliasPlugin } = await rolldown()
const result = await build({
input: entryPoint,
write: false,
cwd,
output: {
format: isESM ? 'esm' : 'cjs',
sourcemap: false,
file: 'out.js',
},
platform: 'node',
transform: {
define: {
...define,
__dirname: JSON.stringify(dirname),
__filename: JSON.stringify(filename),
...isESM ? {} : { 'import.meta.url': JSON.stringify(pathToFileURL(filepath)) },
},
},
external(id) {
if (isAlias(id))
return false
if (id[0] !== '.' && !path.isAbsolute(id) && id !== 'vite-plugin-mock-dev-server')
return true
},
plugins: [aliasPlugin({ entries: alias }), renamePlugin, json5Plugin],
onLog(level, log, defaultHandler) {
if (log.code === 'PLUGIN_TIMINGS' && log.message.includes('vite-mock'))
return
defaultHandler(level, log)
},
})
return {
code: result.output[0].code,
deps: result.output[0].moduleIds.filter(id => !id.endsWith(filename)).map(id => normalizePath(path.relative(cwd, id))),
}
}
catch (e) {
console.error(e)
}
return { code: '', deps: [] }
}