-
-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathpresets.ts
83 lines (76 loc) · 2.45 KB
/
presets.ts
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
import type { Arrayable } from '@antfu/utils'
import { toArray } from '@antfu/utils'
import type { LoadConfigSource } from './types'
export interface SourceVitePluginConfigOptions {
plugins: Arrayable<string>
}
export interface SourceObjectFieldOptions extends Omit<LoadConfigSource, 'rewrite'> {
fields: Arrayable<string>
}
export interface SourcePluginFactoryOptions extends Omit<LoadConfigSource, 'transform'>{
targetModule: string
}
/**
* Retwrite the config file and extract the options passed to plugin factory
* (e.g. Vite and Rollup plugins)
*/
export function sourcePluginFactory(options: SourcePluginFactoryOptions) {
return {
...options,
transform: (source: string) => {
const prefix = `
let __unconfig_data;
let __unconfig_stub = function (data) { __unconfig_data = data };
__unconfig_stub.default = (data) => { __unconfig_data = data };
`
const suffix = 'export default __unconfig_data;'
let code = source
.replace(new RegExp(`import (.+?) from (['"])${options.targetModule}\\2`), 'const $1 = __unconfig_stub;')
.replace('export default', 'const __unconfig_default = ')
if (code.includes('__unconfig_default'))
code += '\nif (typeof __unconfig_default === "function") __unconfig_default();'
return `${prefix}${code}${suffix}`
},
}
}
export function sourceVitePluginConfig(options: SourceVitePluginConfigOptions): LoadConfigSource {
const plugins = toArray(options.plugins)
return {
files: ['vite.config'],
async rewrite(obj) {
const config = await (typeof obj === 'function' ? obj() : obj)
if (!config)
return config
return config.plugins.find((i: any) => plugins.includes(i.name) && i?.api?.config)?.api?.config
},
}
}
/**
* Get one field of the config object
*/
export function sourceObjectFields(options: SourceObjectFieldOptions): LoadConfigSource {
const fields = toArray(options.fields)
return {
...options,
async rewrite(obj) {
const config = await (typeof obj === 'function' ? obj() : obj)
if (!config)
return config
for (const field of fields) {
if (field in config)
return config[field]
}
},
}
}
/**
* Get one field of `package.json`
*/
export function sourcePackageJsonFields(options: Pick<SourceObjectFieldOptions, 'fields'>): LoadConfigSource {
return sourceObjectFields({
files: ['package.json'],
extensions: [],
parser: 'json',
fields: options.fields,
})
}