/
index.ts
96 lines (90 loc) · 2.21 KB
/
index.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
84
85
86
87
88
89
90
91
92
93
94
95
96
import { createUnplugin } from 'unplugin'
import alias from '@rollup/plugin-alias'
import MagicString from 'magic-string'
import { presets } from './config/presets'
import type { Options } from './types'
import { generateCode } from './helpers/generateCode'
const ENTRY_FLAG = 'MOMENT_TO_DAYJS_ENTRY'
export default createUnplugin<Options>((options) => {
const { preset = 'antd' } = options || {}
const plugins = options?.plugins ?? presets[preset].plugins
const replaceMoment = options?.replaceMoment ?? presets[preset].replaceMoment
let entryId: string
return {
name: 'unplugin-moment-to-dayjs',
enforce: 'pre',
vite: {
config: () => {
return replaceMoment
? {
resolve: {
alias: {
moment: 'dayjs',
},
},
}
: {}
},
transformIndexHtml: {
enforce: 'pre',
transform() {
return [{
tag: 'script',
attrs: {
type: 'module',
src: ENTRY_FLAG,
},
injectTo: 'body-prepend',
}]
},
},
},
rollup: {
async resolveId(source, importer, options) {
if (options.isEntry)
entryId = source
return null
},
options: (options) => {
options.plugins = [
alias({
entries: {
moment: 'dayjs',
},
}),
...(options.plugins || []),
]
return options
},
},
webpack(compiler) {
const { resolve } = (compiler as any).options
resolve.alias = {
...resolve.alias,
moment: 'dayjs',
}
},
// transformInclude(id) {
// console.log(id)
// return id.includes(ENTRY_FLAG)
// },
resolveId(source) {
if (source.includes(ENTRY_FLAG))
return ENTRY_FLAG
},
load(id) {
if (id.endsWith(ENTRY_FLAG))
return generateCode(plugins)
},
transform(code, id) {
if (id === entryId) {
const ms = new MagicString(code)
ms.append(generateCode(plugins))
return {
code: ms.toString(),
map: ms.generateMap(),
}
}
},
}
})